Search code examples
swiftsolid-principlesswift-protocols

"init" in Swift's protocols - what for?


Could you please explain why one may want to put initializer in Swift's protocol? I thought that protocols' responsibility is to define what concrete implementation can do, without specyfing implementation details. Isn't initializer such a thing?


Solution

  • Here is a very contrived example:

    protocol P {
        init(a: Int)
    }
    
    class B: P {
        let a: Int
        required init(a: Int) {
            self.a = a
        }
    }
    
    func factory<T: P>(a: Int) -> T {
        return T(a: a)
    }
    
    let b: B = factory(a: 1)
    

    By allowing the Protocol (P) to specify a required initializer, I can write the factory function which needs to make new objects.

    The init doesn't say what you do with the Int that is passed in -- just that it is possible to make P concrete values from an Int.