Skip to content

Instantly share code, notes, and snippets.

@rosstulloch
Last active October 19, 2017 23:15
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 rosstulloch/9aae80d96568be8d5996790ac0214810 to your computer and use it in GitHub Desktop.
Save rosstulloch/9aae80d96568be8d5996790ac0214810 to your computer and use it in GitHub Desktop.
.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