Created
May 12, 2023 00:44
-
-
Save dokun1/b6edbce51085d62159059ec4d50936de to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
enum ComputerModel: String { | |
case apple = "Apple" | |
case windows = "Windows" | |
case linux = "Linux" | |
} | |
enum ComputerError: Error { | |
case tooEarly | |
case tooMany | |
} | |
struct Computer { | |
var yearMade: Int | |
var yearPurchased: Int | |
var model: ComputerModel | |
var make: String | |
init(yearMade: Int, yearPurchased: Int, model: ComputerModel, make: String) throws { | |
if yearMade > yearPurchased { | |
throw ComputerError.tooEarly | |
} | |
self.yearMade = yearMade | |
self.yearPurchased = yearPurchased | |
self.model = model | |
self.make = make | |
} | |
} | |
struct ShoppingCart { | |
private var computers: [Computer] | |
private var maximumContents: Int | |
init() { | |
self.computers = [Computer]() | |
self.maximumContents = 5 | |
} | |
init(maximum: Int) { | |
self.maximumContents = maximum | |
self.computers = [Computer]() | |
} | |
mutating func add(_ computer: Computer) throws { | |
if self.computers.count >= maximumContents { | |
throw ComputerError.tooMany | |
} else { | |
self.computers.append(computer) | |
} | |
// is the amount after greater than the amount before? | |
// is the computer I added valid? | |
// am I below the maxmimum number of computers? | |
} | |
} | |
var cart = ShoppingCart(maximum: 1) | |
func showErrorMessage(_ string: String) { | |
print(string) | |
} | |
do { | |
let computer = try Computer(yearMade: 2020, yearPurchased: 2021, model: .apple, make: "Mac book pro") | |
try cart.add(computer) | |
print("all done!") | |
} catch ComputerError.tooEarly { | |
showErrorMessage("this computer was bought too early!") | |
} catch ComputerError.tooMany { | |
print("This cart has too many computers!") | |
} catch { | |
print(error) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment