Optionals
Optionals are variables that have valid data OR nil.
For example a Non-optional variable is declared like so, and you must initialize it. If you do not initialize it, and you access it, then you’ll get an error:
1 2 |
var maybeAString : String print(maybeAString) //error |
But if you declare it as an Optional, then it will display nil
1 2 |
var maybeAString : String? print(maybeAString) // will produce nil |
For string types, you can assign it an empty string, and call String functions on it:
1 2 3 |
maybeAString = "" maybeAString?.isEmpty // true maybeAString == nil // false |
We use ? to apply Optional Chaining.
Optional chaining lets you safely unwrap this value by placing a question mark (?), instead, after the property, and is a way of querying properties and methods on an optional that might contain nil.
example:
Say you have an optional variable that is initialized to nil.
If you decide to use optional chaining on that nil like the example below, it will send a message to execute function append with a String parameter. Once it sees that the object missingName is nil, it simply won’t do anything. This stays consistent with the original Objective-C language, where if you send a message to nil, nothing will happen.
1 2 |
var missingName : String? = nil missingName?.append("hahahahha") |
However, if you were to use exclamation mark (“!”), which Force UnWrapping, it means you are sure the variable is NOT nil. If its nil, then the program will crash like so:
1 2 |
var missingName : String? = nil let temp = missingName! |
If you were to access the courses property through an exclamation mark (!) , you would end up with a runtime error because it has not been initialized yet.