I know Enum is used as below , what about Array or Dictionary?
enum VendingMachineError: Error {
case invalidSelection
case insufficientFunds(coinsNeeded: Int)
case outOfStock
}
throw VendingMachineError.insufficientFunds(coinsNeeded: 5)
I know Enum is used as below , what about Array or Dictionary?
enum VendingMachineError: Error {
case invalidSelection
case insufficientFunds(coinsNeeded: Int)
case outOfStock
}
throw VendingMachineError.insufficientFunds(coinsNeeded: 5)
Any type conforming to the Error
protocol can be used. If you really want
to throw an array then it suffices to declare conformance to the protocol:
extension Array: Error {}
do {
throw [1, 2, 3]
} catch {
print("Failed:", error) // Failed: [1, 2, 3]
}
Here is more realistic example, using a struct
to throw
an error with additional information (a simplified example from
Swift 3 errors with additional data):
struct ParserError: Error, LocalizedError {
let line: Int
public var errorDescription: String? {
return "Parser error at line \(line)"
}
}
func parse() throws {
throw ParserError(line: 13)
}
do {
try parse()
} catch let error {
print(error.localizedDescription)
}
Output:
Parser error at line 13