Swift: Implementing Protocol Initializer in a Class

前端 未结 2 850
长发绾君心
长发绾君心 2021-01-22 03:34

I am trying to understand why Swift enforces a class that conforms to a protocol with an initializer to be marked as required. This essentially enforces any subclasses to also i

2条回答
  •  醉话见心
    2021-01-22 03:54

    You're not force to implement the initializer in the subclass. Consider this example, which compiles just fine:

    protocol SomeProtocol {
        init(someParameter: Int)
    }
    
    
    class SomeClass: SomeProtocol {
        required init(someParameter: Int) {
            // initializer implementation goes here
            print(someParameter)
        }
    }
    
    
    class SomeSubclass: SomeClass {
        // Notice that no inits are implemented here
    }
    
    _ = SomeClass(someParameter: 123)
    _ = SomeSubclass(someParameter: 456)
    

提交回复
热议问题