Protocol Extension Initializer

后端 未结 4 1121
谎友^
谎友^ 2020-12-10 04:34

I would like to know what the protocol equivalent is for an initializer in a simple class that only contains initializing functionality and is only intended to be extended i

4条回答
  •  -上瘾入骨i
    2020-12-10 05:17

    You have to provide a valid chain of init for creating an instance of a class and that limits your options for initializers in protocols.

    Since your protocol can't be certain to cover all members of the class that uses it, any initializer you declare in your protocol will need to delegate initialization of the "unknown" members of the class to another initializer provided by the class itself.

    I adjusted your example to illustrate this using a basic init() as the delegation initializer for the protocol.

    As you can see, this requires that your class implement initial values for all members when init() is called. In this case I did that by providing default values in each member's declaration. And, since there isn't always an actual initial value for some members, I changed them to auto-unwrap optionals.

    And to make thinks more interesting, your class cannot delegate initialization to a protocol supplied initializer unless it does so through a convenience initializer.

    I wonder if all these restrictions are worth the trouble. I suspect you're trying to use a protocol because you need a bunch of common variables to be initialized consistently between classes that implement the protocol. Perhaps using a delegate class would provide a less convoluted solution than protocols (just a thought).

    protocol Thing:AnyObject
    {
        var color:UIColor! { get set }
        init()
    }
    
    extension Thing 
    {    
        init(color:UIColor)
        {  
           self.init()
           self.color = color
        }
    }
    
    class NamedThing:Thing 
    {
        var name:String!   = nil
        var color:UIColor! = nil
    
        required init() {}
    
        convenience init(name:String,color:UIColor) 
        {
            self.init(color:color)
            self.name = name
        }
    }
    

提交回复
热议问题