Optionals: a data structure that may or may not have a value.
Syntax:var optionalNumber: Int?
Unlike in Objective-C, variables generally cannot be defined as nil. Optionals provide a safe mechanism to deal with the case where a value might not exist. Missing values will be nil, while actual values will be wrapped in an optional. An optional must be unwrapped to access its underlying value. If you are sure the value exists, use the forced-unwrapping operator "!", otherwise use optional binding to test and unwrap at the same time.
In this first example, the optional is explicitly checked for nil before being unwrapped with the "!" operator.wheelCount["bicycle"] = 2 wheelCount["tricycle"] = 3 wheelCount["Ferrari"] = 4 let numWheels: Int? = wheelCount["unicycle"] if numWheels == nil { println("Error: no data") } else { let wheels: Int = numWheels! println("Wheels: \(wheels)") }
wheelCount["bicycle"] = 2 wheelCount["tricycle"] = 3 wheelCount["Ferrari"] = 4 let numWheels: Int? = wheelCount["unicycle"] if let wheels = numWheels { println("Wheels: \(wheels)") }
func findIndexOfString(string: String, array: String[]) -> Int? { for (index, value) in enumerate(array) { if value == string { return index } } return nil } var fruit = ["Apple","Banana","Lemon","Lime"] if let index = findIndexOfString("Lime",fruit) { println("\(fruit[index]) is on the list") } else { println("Need to add it") }
class Person { var residence: Residence? } class Residence { var address: Address? } class Address { var buildingNumber: String? var streetName: String? var apartmentNumber: String? } let sam = Person() // the long way var addressNumber: Int? if let home = sam.residence { if let postalAddress = home.address { if let building = postalAddress.buildingNumber { if let convertedNumber = building.toInt() { addressNumber = convertedNumber } } } } // the optional chaining way var addressNumber: Int? addressNumber = sam.residence?.address?.buildingNumber?.toInt() // optional binding combined with optional chaining if let addressNumber = sam.residence?.address?.buildingNumber?.toInt() { addEntry("Sam", addressNumber) }