Last active
December 13, 2018 14:35
-
-
Save LeeKahSeng/dcf19a83d20b6b85ef2e7c5b9df02c8a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Bird { | |
var name: String | |
init(name: String) { | |
self.name = name | |
} | |
} | |
class Chicken: Bird { | |
let canFly = false | |
} | |
class Eagle: Bird { | |
let canFly = true | |
func fly() { | |
print("Eagle is flying.") | |
} | |
} | |
let chicken = Chicken(name: "Chicky") | |
// Casting from subclass to parent class by using 'as' | |
let bird1 = chicken as Bird // Cast sucessful, bird1 type is Bird | |
let bird2 = chicken as? Bird // Warning: Forced cast from 'Chicken' to 'Bird' always succeeds | |
let bird3 = chicken as! Bird // Warning: Forced cast from 'Chicken' to 'Bird' always succeeds | |
// Add chicken into array of type [Bird] | |
let birds: [Bird] = [chicken] | |
let chicken1 = birds[0] as Chicken // Compile error: 'Bird' is not convertible to 'Chicken' | |
let chicken2 = birds[0] as? Chicken // Cast successful: chicken2 type is Chicken? | |
let chicken3 = birds[0] as! Chicken // Cast successful: chicken3 type is Chicken | |
let eagle1 = birds[0] as Eagle // Compile error: 'Bird' is not convertible to 'Eagle' | |
let eagle2 = birds[0] as? Eagle // Cast failed: eagle2 is nil | |
let eagle3 = birds[0] as! Eagle // Cast failed: Trigger runtime error | |
// Using optional binding to access conditional cast result | |
if let myChicken = birds[0] as? Chicken { | |
print(myChicken.name) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment