Last active
October 19, 2017 23:15
-
-
Save rosstulloch/9aae80d96568be8d5996790ac0214810 to your computer and use it in GitHub Desktop.
.self vs .Type vs type(of:)
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
protocol HasInit { | |
init() | |
func sayHi() | |
} | |
extension HasInit { | |
func sayHi() { print("Hi from an instance of \(type(of: self))") } | |
} | |
class A:HasInit { | |
required init() { print("Init of \(type(of: self))") } | |
} | |
func makeInstance<T>(_ thetype:T.Type ) -> HasInit? { | |
return (thetype as? HasInit.Type)?.init() | |
} | |
let aClassType = A.self | |
let aInstance = aClassType.init() | |
aInstance.sayHi() | |
let aaClass = type(of: aInstance) | |
makeInstance(aaClass)?.sayHi() | |
struct AS:HasInit { | |
init() { print("Init of \(type(of: self))") } | |
} | |
let asStructType = AS.self | |
let asInstance = asStructType.init() | |
asInstance.sayHi() | |
makeInstance(type(of: asInstance))?.sayHi() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment