Type Casting

    In this lesson, you learn how to convert types in objects that are created with classes and structs. In fact, if you use Storyboard in iOS, you must know type casting.

    Problem

    1. How do you distinguish between as, as?, as!?

    Type Casting in UIKit

    You might have seen,

    You’ve converted UILabel to UIView. UILabel is a subclass of UIView. Let us attempt to replicate the phenomenon with custom classes.

    Design a class called, Human that contains a single method.

    1. class Human {
    2. func introduce() {
    3. print("Hi, I'm a human")
    4. }
    5. }

    Human Subclass

    Design Korean and Japanese which inherit from the Human class.

    1. class Korean: Human {
    2. func singGangNamStyle() {
    3. print("Oppa Gangnam Style")
    4. }
    5. }
    6. func doNinja() {
    7. print("Shhh.....")
    8. }
    9. }

    Check if all good

    1. let bob = Korean()
    2. bob.introduce() // "Hi, I'm a human"
    3. bob.singGangNamStyle() // "Oppa Gangnam Style"

    Type Casting

    Upcasting occurs when an object converts its type to the base class. In the early above, you’ve upcasted UILabel to UIView using as.

    Upcasting Example in Swift Struct

    1. var name = "Bob" as Any
    2. var number = 20 as Any

    Downcasting

    Downcasting is the opposite. You may downcast Any to String. However, it may fail since Any could contain many types. Analogous to optionals, there are two ways to downcast: Force downcasting or Implicit downcasting

    It does not return an optional type. but if it fails, it crashes.

    1. // Force Downcasting
    2. let newValue = anyArray[0] as! String

    Implicit Downcasting

    It returns an optional type. If it fails, it returns nil.

    1. let newNewValue = anyArray[0] as? Int
    2. print(newNewValue) // Optional(20)

    Create Instances

    1. let humans: [Human] = [shion as Human, lee as Human, kenji as Human, park as Human]
    1. let humans: [Human] = [shion, lee, kenji, park]
    2. let humans = [shion, lee, kenji, park]

    Loop

    1. for human in humans {
    2. if let korean = human as? Korean {
    3. korean.singGangNamStyle()
    4. }
    5. if let japanese = human as? Japanese {
    6. japanese.doNinja()
    7. }
    8. }

    Usage in iOS Development

    Typecasting can be used to group UI Components and add attributes as a whole.

    Another Example

    To fetch a view controller from Storyboard, downcast to identify the designated view controller.

    1. let storyboard = UIStoryboard(name: "Main", bundle: nil)
    2. let vc = storyboard instantiateViewController(withIdentifier: "VC")
    3. // type of vc = UIViewController
    4. let vc = storyboard instantiateViewController(withIdentifier: "VC") as! VC

    Reference

    Conclusion

    I lied. I said type casting allowed to convert types in classes. However, you may also convert Int and String to Any even though they are made up of structs, not classes.

    Unnecessary type casting is not recommended among iOS developers because it causes a massive headache from casting back and forth. There is an alternative to go about. You will learn how to group objects together through Protocol Oriented Swift in Chapter 3. I know you are excited. Learn fast, but stay patient and consistent.