-
Notifications
You must be signed in to change notification settings - Fork 2
Overview_Optionals
One of the main benefits of Swift is type safety. Attempting to access a property with an unexpected nil value is a major cause of bugs. Optionals exist to remove any uncertainty around nil.
Using Optionals well will give you confidence when accessing variables in your code. At compile time, you will always know if the property you're accessing might have a value or must have a value.
Properties can be declared as variables (var) or constants (let). For each of these types of declarations, they can be:
- Optional (variable) by adding
?after the type. This can either be declared withvarorlet. - Required (constant) by declaring it as
let(but without the?). - Optional, but implicitly unwrapped (by adding
!after the type. Use this withvardeclarations).
For example:
struct MyExampleStruct {
var firstName : String? // Optional
let lastName : String // Non-Optional const. This value MUST be set during initialization.
let apiKey : String = "xQ7tt4$" // Non-Optional const, but initialized here.
var gender : String! // Implicitly Unwrapped Optional
init(lastname: String) {
self.lastName = lastname
}
init(firstname: String?, lastname: String, gender: String!) {
self.firstName = firstname
self.lastName = lastname
self.gender = gender
}
}
Note that the following
initwill fail, because apiKey is a constant (let) whose value had already been assigned when declared:
init(firstname: String?, lastname: String, apiKey: String!, gender: String!) {
self.firstName = firstname
self.lastName = last name
self.apiKey = apiKey
self.gender = gender
}
var s = MyExampleStruct(lastname: "Fred")
//{firstName: nil, lastName: "Fred", apiKey: "xQ7tt4$", gender: nil}
var u = MyExampleStruct(firstname: "Howard", lastname: "Duck", gender: "M")
//{firstName: "Howard", lastName: "Duck", apiKey: "xQ7tt4$", gender: "M"}
Where possible, strive to keep your properties safe, meaning Optional. Valid reasons for non-safety (implicitly unwrapped optionals) are:
- Instances where you are absolutely certain that at run-time, they will never be nil (
@IBOutletis a good example of this). - Lazy vars (but with a caveat, discussed below).