Skip to content

Instantly share code, notes, and snippets.

@xaphod
Created November 28, 2019 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xaphod/286a823e498e61784b9a1cf37b0fe442 to your computer and use it in GitHub Desktop.
Save xaphod/286a823e498e61784b9a1cf37b0fe442 to your computer and use it in GitHub Desktop.
Swift type checking
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
Copy link

amomchilov commented Nov 28, 2019

import Foundation

class Animal: NSObject {}// You're forced to "buy into" NSObjectProtocol for `isKind(of:)`
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 {
	object.isKind(of: tType)
//	print(object is tType)
	// question: does object inherit from tType?
}

func hereIsTheSolution<T: Animal>(object: Animal, ofType: T.Type) -> Bool {
	return object is T
}

print(hereIsTheSolution(object: c, ofType: Dog.self)) // should return false
print(hereIsTheSolution(object: gd, ofType: Dog.self)) // should return true

@xaphod
Copy link
Author

xaphod commented Nov 28, 2019

Thanks!

@officialmanishgupta
Copy link

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