Optionals
Welcome to the first lesson of The Swift Fundamentals. When I first started programming in Swift, I took courses from Udemy, Treehouse, Lynda, and many more. Yet, I could not understand what those s and !
s stood for. Xcode kept telling me what to do on the left side, causing more problems. It seemed like no instructor could explain the reasoning behind how to use optionals, and most importantly, why Swift engineers have implemented a such feature that is unique compared to other programming languages. Today, You will discover the why with me.
Problem
Why did Swift engineers implement optionals
?
- Every variable type must be defined (Implicit/Explicit)
- The type is inferred based on the value
Fetching Profile Picture
When you fetch a profile picture from Facebook, it may return no value, a.k.anil
. However, you may not store nil
to a normal type based on the rule above.
// Successful
let myProfileImageURL: String = "https//facebook.com/bobthedeveloper"
// Error
let myProfilePictureURL: String = nil
let myName: String? = nil
let yourName: String? = "Bob Lee"
print(myName) // nil
print(yourName) // Optional("Bob Lee")
let bobAge: Int? = nil
let danAge: Int? = 3
Optionals Rules
- Optionals/Normal Types do not interact with each other
There are two ways to convert/unwrap optional types to normal types
- Forced unwrapping
- Implicit unwrapping
You may convert by inserting !
at the end of the variable. Forced Unwrapping should be avoided since it causes a crash if the optional type contains nil
since a normal type can’t store nil
.
let profileImageFromFacebook: String? = "ImageURL..."
print(profileImageFromFacebook) // Optional
Now, let us unwrap profileImageFromFacebook
.
var image = profileImageFromFacebook! // String? converted to String
print(image) // Normal Type
print(profileImageFromFacebook!) // Normal Type
You must unwrap to work with variables.
var image: String? = nil
let normalImage = image! // let normalImage = nil
// Error
Implicit unwrapping is a safe way to convert. If the optional type contains nil
, it does not break the system. Instead, it ignores. Implicit unwrapping is an added feature to an else-if
statement.
if let normalImage = imageFromFaceBook {
print(normalImage)
} else {
}
Now normalImage
contains a normal type of String
. You may use the normalImage
constant within the if
block. On the contrary, if imageFromFaceBook
contains nil
, Swift executes the else
block instead.
Conclusion
In the next lesson, you will learn why ?
and automatically appear when you create an object and access its properties and methods.