Type casting

 Type casting

Type casting in Swift allows you to check and convert an object from one type to another. This is useful when working with inheritance hierarchies or when you need to ensure that an object conforms to a particular type before performing operations on it.


  1. as? (Optional Casting): This operator attempts to cast an object to a specified type and returns an optional value. If the cast fails, it returns nil.

  2. as! (Forced Casting): This operator attempts to cast an object to a specified type and returns the value if the cast is successful. If it fails, it causes a runtime crash.

  3. is (Type Checking): This operator checks whether an object is of a specified type.


Example Code

swift


import UIKit
class Animal { func speak() { print("Animal makes a sound") } } class Dog: Animal { func bark() { print("Dog barks") } } class Cat: Animal { func meow() { print("Cat meows") } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let animals: [Animal] = [Dog(), Cat(), Dog()] for animal in animals { // Using `is` to check the type if animal is Dog { print("This animal is a Dog") } else if animal is Cat { print("This animal is a Cat") } // Using `as?` for optional casting if let dog = animal as? Dog { dog.bark() // Safe to call Dog-specific methods } else if let cat = animal as? Cat { cat.meow() // Safe to call Cat-specific methods } // Using `as!` for forced casting (use with caution) // Ensure animal is indeed a Dog to avoid crash if let dog = animal as? Dog { dog.bark() // Safe to call Dog-specific methods } } } }

Explanation:

  1. is Operator:

    • Checks whether each animal in the animals array is of type Dog or Cat.
    • Prints the type accordingly.
  2. as? Operator:

    • Safely attempts to cast the animal to Dog or Cat and calls specific methods if the cast is successful.
    • If the cast fails, it does nothing.
  3. as! Operator:

    • Although it's not used directly in the example above, it’s included for completeness.
    • as! is used when you are certain about the type and want to force the cast. This is risky as it can cause a runtime crash if the cast is incorrect.

Important: Prefer using as? for optional casting and avoid as! unless you're certain of the type to prevent runtime crashes.

Comments

Popular posts from this blog

Complete iOS Developer Guide - Swift 5 by @hiren_syl |  You Must Have To Know 😎 

Debugging

Swift Fundamentals You Can’t Miss! A List by @hiren_syl