Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run?
let text = "12a"
let number = Int(text)!
print(number + 1)The program crashes
- Expecting a compile error: the compiler accepts
Int(text)!, since whether the text is a number becomes known only at run time, where!stops the program. - Expecting
13:Int("12a")does not read the leading digits, it rejects the whole text and givesnil, and!onnilcrashes.
- How would you change the second line so the program keeps running when the text is not a number?
- When is force unwrapping with
!acceptable?