swiftoption-typeoptional-values

Is it necessary to set variable 'possibleIntegerValue' to 'optional Int(Int?)' or it is ok to set 'possibleIntegerValue' to the type 'Int' instead?


I'm new to Swift and is trying to learn the concept of optional values. My question is, within the context of the code before, is necessary to set variable 'possibleIntegerValue' to 'optional Int(Int?)' or it is ok to omit the ? sign and set 'possibleIntegerValue' to the type 'Int' instead?

What kind of impact doesit make if I indeed change the type from optional Int to Int?

let numberSymbol: Character = "三"  // Simplified Chinese for the number 3
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "١", "一", "๑":
    possibleIntegerValue = 1
case "2", "٢", "二", "๒":
    possibleIntegerValue = 2
case "3", "٣", "三", "๓":
    possibleIntegerValue = 3
case "4", "٤", "四", "๔":
    possibleIntegerValue = 4
default:
    break
}
if let integerValue = possibleIntegerValue {
    print("The integer value of \(numberSymbol) is \(integerValue).")
} else {
    print("An integer value could not be found for \(numberSymbol).")
}

Solution

  • Optionals allow you to have a case where there is no value. You have the following options for declaring a variable:

    var possibleIntegerValue: Int?      // Optional Int
    var possibleIntegerValue: Int = 0   // Not optional but must *always* have a value
    var possibleIntegerValue: Int!      // Implicitly unwrapped Optional Int
    

    In the third option above, you are guaranteeing that possibleIntegerValue will have a value by the time it is first used (or your app will crash with an uncaught exception).

    Since your switch statement has a default that does not give possibleIntegerValue a value, using an Optional Int seems appropriate.