How to define initializers in a protocol extension?

后端 未结 4 485
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-30 20:06
protocol Car {
     var wheels : Int { get set}

     init(wheels: Int)

}

extension Car {
    init(wheels: Int) {
        self.wheels = wheels
    }
}
<
4条回答
  •  旧时难觅i
    2021-01-30 20:39

    @Qbyte is correct.

    In addition, you can take a look at my Configurable

    In that I have Initable protocol

    public protocol Initable {
        // To make init in protocol extension work
        init()
    }
    
    public extension Initable {
        public init(@noescape block: Self -> Void) {
            self.init()
            block(self)
        }
    }
    

    Then in order to conform to it

    extension Robot: Initable { }
    

    I have 2 ways, using final or implement init

    final class Robot {
        var name: String?
        var cute = false
    }
    
    class Robot {
        var name: String?
        var cute = false
    
        required init() {
    
        }
    }
    

提交回复
热议问题