Created
November 28, 2019 15:06
-
-
Save xaphod/286a823e498e61784b9a1cf37b0fe442 to your computer and use it in GitHub Desktop.
Swift type checking
This file contains hidden or 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
import UIKit | |
protocol Animal {} | |
class Cat : Animal {} | |
class Dog : Animal {} | |
class GreatDane : Dog {} | |
let c = Cat() | |
let d = Dog() | |
let gd = GreatDane() | |
func hereIsTheQuestion(object: Animal, tType: Animal.Type) -> Bool { | |
// question: does object inherit from tType? | |
} | |
hereIsTheQuestion(object: c, tType: Dog.self) // should return false | |
hereIsTheQuestion(object: gd, tType: Dog.self) // should return true |
amomchilov
commented
Nov 28, 2019
•
Thanks!
w/o NSObject
protocol Animal {}
class Dog: Animal {}
class Cat: Animal {}
class GermanShepard: Dog {}
var aDog: Animal = Dog()
var gs: Dog = GermanShepard()
var c: Cat = Cat()
print(aDog is Cat) // prints true
print(type(of: aDog)) // prints Dog
func check<T: Animal>(object: Animal, inType: T.Type) -> Bool {
return object is T
}
check(object: c, inType: Dog.self) // prints false
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment