0

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).")
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137
  • 1
    You would need to assign 0 or a default value to it instead of leaving it nil – Leo Dabus Jan 20 '16 at 05:20
  • 1
    You can leave it as is now. possibleIntegerValue:Int? And obviously you need it to be nil in case none of the switch cases match the numberSymbol. – Shripada Jan 20 '16 at 05:23

1 Answers1

3

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.

Michael
  • 8,891
  • 3
  • 29
  • 42