Jack Guo
Jack Guo

Reputation: 4664

Can I implement default initialization in protocol in Swift

I have a variety of classes that all conform to a single protocol and share the same initialization method. Is there a way to implement the initialization in the protocol? So I don't have to copy the code in every class. This is what I have so far

protocol someProtocol {
    init(data: Data)
}

class ObjectA: someProtocol {
    let data: Data
    required init(data: Data) {
        self.data = data
    }
}

class ObjectB: someProtocol {
    let data: Data
    required init(data: Data) {
        self.data = data
    }
}

Upvotes: 0

Views: 394

Answers (1)

Fogmeister
Fogmeister

Reputation: 77641

You can’t do this as the protocol and protocol extension have no knowledge about the properties in the objects that conform to them and so you cannot initialise all the story properties.

I’m sure there are other runtime reason about type inference too but this one is probably the most simple to explain.

Upvotes: 1

Related Questions