Swift - what's the difference between metatype .Type and .self?

前端 未结 4 741
一生所求
一生所求 2020-12-02 10:52

What\'s the difference between metatype .Type and .self in Swift?

Do .self and .Type return a struct

4条回答
  •  春和景丽
    2020-12-02 10:56

    This was one of those topics that confused the hell out of me today.

    I was writing a generic function:

    func foo(ofType: T.Type) {
        T.bar()
    }
    

    And tried calling it as follows:

    foo(ofType: ClassImplementingProtocol.Type) // Compiler error
    

    Spent about 30 min researching why it wasn't working. Then I tried this:

    foo(ofType: ClassImplementingProtocol.self) // Works
    

    Turns out Xcode's code completion is very bad at showing the difference between meta types and types... From the code completion pop-up it looks like .self and .Type are the same thing:

    But the "explain like im 5" of it is, when you have a method parameter of Class.Type, it is expecting an instance of Class.Type.

    Class.self returns an instance of Class.Type, whereas Class.Type is referring to Class.Type...

    Very unclear if you ask me.

提交回复
热议问题