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
- 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.
class Human {
func introduce() {
print("Hi, I'm a human")
}
}
Human Subclass
Design Korean
and Japanese
which inherit from the Human
class.
class Korean: Human {
func singGangNamStyle() {
print("Oppa Gangnam Style")
}
}
func doNinja() {
print("Shhh.....")
}
}
Check if all good
let bob = Korean()
bob.introduce() // "Hi, I'm a human"
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
var name = "Bob" as Any
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.
// Force Downcasting
let newValue = anyArray[0] as! String
Implicit Downcasting
It returns an optional type. If it fails, it returns nil
.
let newNewValue = anyArray[0] as? Int
print(newNewValue) // Optional(20)
Create Instances
let humans: [Human] = [shion as Human, lee as Human, kenji as Human, park as Human]
let humans: [Human] = [shion, lee, kenji, park]
let humans = [shion, lee, kenji, park]
Loop
for human in humans {
if let korean = human as? Korean {
korean.singGangNamStyle()
}
if let japanese = human as? Japanese {
japanese.doNinja()
}
}
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.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard instantiateViewController(withIdentifier: "VC")
// type of vc = UIViewController
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.