Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
.self vs .Type vs type(of:)
protocol HasInit {
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()
let aaClass = type(of: aInstance)
struct AS:HasInit {
init() { print("Init of \(type(of: self))") }
let asStructType = AS.self
let asInstance = asStructType.init()
makeInstance(type(of: asInstance))?.sayHi()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.