Optionals are a generic enum type that acts as a wrapper. This wrapper allows a variable to have one of two states: the value of the user-defined type or nil
, which represents the absence of a value.
This ability is particularly important in Swift because one of the stated design objectives of the language is to work well with Apple's frameworks. Many (most) of Apple's frameworks utilize nil
due to its ease of use and significance to programming patterns and API design within Objective-C.
In Swift, for a variable to have a nil
value, it must be an optional. Optionals can be created by appending either a !
or a ?
to the variable type. For example, to make an Int
optional, you could use
var numberOne: Int! = nil
var numberTwo: Int? = nil
?
optionals must be explicitly unwrapped, and should be used if you aren't certain whether or not the variable will have a value when you access it. For example, when turning a string into an Int
, the result is an optional Int?
, because nil will be returned if the string is not a valid number
let str1 = "42"
let num1: Int? = Int(str1) // 42
let str2 = "Hello, World!"
let num2: Int? = Int(str2) // nil
!
optionals are automatically unwrapped, and should only be used when you are certain that the variable will have a value when you access it. For example, a global UIButton!
variable that is initialized in viewDidLoad()
//myButton will not be accessed until viewDidLoad is called,
//so a ! optional can be used here
var myButton: UIButton!
override func viewDidLoad(){
self.myButton = UIButton(frame: self.view.frame)
self.myButton.backgroundColor = UIColor.redColor()
self.view.addSubview(self.myButton)
}