Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
.self vs .Type vs type(of:)
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