Insights from Our Experts
Optionals in Swift
Optionals is something new for a non-swift iOS developer. Although it is similar to ‘nullable’ in objective-c, the use of optionals in Swift is way beyond that. Optionals prevent run-time errors caused due to the absence of values. In swift, we cannot define a variable(or a constant) as ‘nil’. Every variable is expected to have some value. so we can declare a variable as optional, by adding a question mark after its type.
Now the value of ‘nilString’ is taken to be nil, as far as there is no value in it. But, why do we this??? Remember Swift is known as a safe language. Take a situation in which a nil parameter is passed as an argument to a function, What if we do some operations on it without knowing that it doesn’t have any value?. it will compile just fine but will cause run time errors. Optionals are used to avoid this kind of situations.
We can access the value of an optional in two ways.
By adding an exclamation mark(!) after the variable. This is called Forced unwrapping. i.e, we are forcefully accessing the underlying value of it. Forced unwrapping is not recommended unless you are 100% sure that the optional contains value in it. If it doesn't have any value, it will cause runtime errors
By adding a question mark(?) after the variable. This is called Optional chaining but is used only to access the properties, methods or subscripts of an optional. Here, if the optional contains any value, the value is returned, otherwise ‘nil’ is returned. This method is a better alternative to forced unwrapping because it won’t cause any error due to the absence of value.
Choosing the safe way
Both of the above ways fail if there is no value in it, so it is always safe to check if the optional contains any value before using it. This can be done by Optional binding. i.e.
The code in the braces is executed if the optional has any value in it. If it is ‘nil’, the code in the else loop is executed.
Now if we are very much sure that the optional always contain some value, then we can make it an Implicitly unwrap optional. This is done by declaring it using an exclamation mark(!).
We can access it using its name since there is no need to unwrap it every time.
One way to use the optional is that we can assign some other value to a variable if it is empty. This is done by nil coalescing operator(??).
If the nilString is empty, the value of defaultString is assigned to originalString.
Optionals is a useful concept you can use when you are programming in Swift. Did you notice all the outlets of UI elements are implicitly unwrapped optionals. This shows the importance of it. All the basic concepts of optionals are discussed here, you can refer to Apple Docs to know more about it.