Back to questions
JuniorTheoryCommon
What does the program print?
enum ParseError: Error {
case badFormat
}
func parse(_ text: String) throws -> Int {
guard let n = Int(text) else {
throw ParseError.badFormat
}
return n
}
let a = (try? parse("8")) ?? -1
let b = (try? parse("8x")) ?? -1
print(a, b)8 -1
- Expecting
8 0: thinkingtry?turns an error into zero. It givesnil, and only?? -1decides what stands in its place. - Expecting a crash: confusing
try?withtry!. Onlytry!stops the program on an error;try?turns the error intonil.
- What would
bhold if the parentheses aroundtry? parse("8x")were removed? - When is
try?the wrong choice because the caller needs the reason for the error?