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?

    1. Every variable type must be defined (Implicit/Explicit)
    2. 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.

    1. // Successful
    2. let myProfileImageURL: String = "https//facebook.com/bobthedeveloper"
    3. // Error
    4. let myProfilePictureURL: String = nil
    1. let myName: String? = nil
    2. let yourName: String? = "Bob Lee"
    3. print(myName) // nil
    4. print(yourName) // Optional("Bob Lee")
    5. let bobAge: Int? = nil
    6. let danAge: Int? = 3

    Optionals Rules

    1. Optionals/Normal Types do not interact with each other

    There are two ways to convert/unwrap optional types to normal types

    1. Forced unwrapping
    2. 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.

    1. let profileImageFromFacebook: String? = "ImageURL..."
    2. print(profileImageFromFacebook) // Optional

    Now, let us unwrap profileImageFromFacebook.

    1. var image = profileImageFromFacebook! // String? converted to String
    2. print(image) // Normal Type
    3. print(profileImageFromFacebook!) // Normal Type

    You must unwrap to work with variables.

    1. var image: String? = nil
    2. let normalImage = image! // let normalImage = nil
    3. // 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.

    1. if let normalImage = imageFromFaceBook {
    2. print(normalImage)
    3. } else {
    4. }

    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.