Optionals (?) in Swift

Pandurang Yachwad
Apps Studio
Published in
2 min readMar 19, 2017

Optionals is one of the great thing in Swift but also working with it can be bit clumsy sometimes. Unwrapping and checking if there is value can be time consuming and get tempted to add exclamation (!) mark to force unwrap the value. It’s dangerous as force unwrapping leads to crash of app if optional doesn’t have a value.

Here is brief about what’s optionals and different types of optionals usage.

What’s Optionals: Optionals are value type in swift with “there is some value and value is ‘X’” or “there isn’t any value at all”. It’s powerful Enum with values None or Some(T). It creates the safe variables and avoid the runtime crash by initializing variables with nil.

var str: String? print(str) // prints null
var str: String print(str) // compile time error as variable is used before initialization

Here are different ways to handle the optionals in the code base.

  • Forced unwrapping: If variable has been defined as optional, it’s required to unwrap it before it’s been used

var str: String? str = “Hello World!” print(str) // It will print — Optional(“Hello World!”)
print(str!) // It will print — “Hello World!”

  • Automatic unwrapping: Alternatively, variable can be defined with automatic unwrapping option. It would be “!” instead of “?”

var str: String! str = “Hello World!”
print(str) // It will print — “Hello World!”

  • Optional Binding: It’s the way to check if optional type variable has value and if it has value, it would be assigned to temporary variable / constant

var str: String? str = “Hello World!”
if let str = str{
print(str) // It will print — “Hello World!”
}

  • Nil-Coalescing Operator: The Nil-Coalescing Operator (a ?? b) unwraps an optional if there is value or returns a default value. The expression b must match the value type stored in a.

var str: String? let newStr = str ?? “Hello there..”
print(newStr) // It will print — “Hello there..”

  • Optional Chaining: It’s process of calling/querying methods, properties, subscripts on an optional which might have nil value. If optional have value, the property, methods, subscripts will return value otherwise it would return nil.

func albumReleased(year: Int) -> String? {
switch year {
case 2006: return “Taylor Swift”
case 2008: return “Fearless”
case 2010: return “Speak Now”
case 2014: return “1989”
default: return nil
}
} print(albumReleased(year: 2006)?.uppercased()) // It will print — TAYLOR SWIFT

--

--

Pandurang Yachwad
Apps Studio

Mobile App Developer and hustler. Life is short, utilize to fullest. Just do it!