Why must constructing an object of class type 'someClass' with a metatype value use a 'required' initializer?

后端 未结 1 1171
离开以前
离开以前 2021-02-07 07:31
class Animal {
    class func generate() -> Animal {
        return self()
    }
}

The compiler complains constructing an object of class ty

1条回答
  •  不知归路
    2021-02-07 08:00

    Consider the case where we also have a subclass:

    class SomeClass {
    
    }
    
    class SomeSubclass : SomeClass {
    
    }
    

    If you store the class type in a variable:

    var anotherClass = SomeClass.self
    

    The variable anotherClass is of type SomeClass.Type.

    You can later assign this variable to a subclass:

    anotherClass = SomeSubclass.self
    

    This is valid because SomeSubclass.Type is a SomeClass.Type. At this point, anotherClass() would fail if the initializer is not implemented in the subclass. This is what the compiler is protecting against.

    In your sample code, this is impossible: you used let instead of var so changing the type is impossible. It may be that the safety checks just aren't nuanced enough to notice this.

    0 讨论(0)
提交回复
热议问题