Swift metatype (Type, self) -
i trying understand : "self, dynamictype, type
". have code :
class someclass {} let cls : someclass.type = someclass.self let cls2 : someclass = someclass()
are cls
, cls2
same thing ?
can give detail differences ?
no, cls
, cls2
different things. easiest way understand difference extend example this:
class someclass { class func doit() { print("i'm class method. belong type.") } func doitonlyifinstanceofthistype() { print("i'm instance method. belong type instance.") } }
and let's take cls
:
let cls : someclass.type = someclass.self cls.doit()
that print i'm class method. belong type.
. cannot invoke this:
cls.doitonlyifinstanceofthistype() // causes compilation error, pro tip: can use method func property, i'll add explanation later
let's take cls2
. visible method of doitonlyifinstanceofthistype
because it's instance method (of type).
let cls2 : someclass = someclass() cls2.doitonlyifinstanceofthistype()
so difference between them cls
type , cls2
instance of type.
a little bit more knowledge why someclass.self , someclass()?
the type of class exists in memory (it has example own methods), singleton representing type (not instance of type - that's different). if call self
on type someclass.self
singleton instance representing someclass
type.
someclass()
invokes init()
method of someclass
, constructor creates instance of someclass
.
pro tip
you can manipulate type instance function (like closures/blocks in objc). it's generated class method. must pass instance of type take method argument, this:
let myfunc :()->() = cls.doitonlyifinstanceofthistype(cls2) myfunc()
Comments
Post a Comment