Mijail Mijail - 6 months ago 8
Swift Question

Is there a way to make a default implementation on a protocol on Swift?

So I have this protocol

protocol Syncable {
func sync()
}


then I want to create another protocol which implements the first one but also specifies other functions to implement like this:

protocol Repository:Syncable {

func propagateTop()
func propagateLow()

override func sync() {
propagateTop()
propagateLow()
}
}


So in this way the ones who implement
Repository
have to implement the two functions without the need of knowing or implementing the
sync
one.

Is there anyway to force this?

I tryed making
Repository
a class and make subclasses of it for every
Repository
I want, but that doesn't force that every subclass should implement that 2 methods.

Answer

Yes, you could write an extension:

protocol Repository: Syncable {
    func propagateTop()
    func propagateLow()
}

extension Repository {
    func sync() {
        propagateTop()
        propagateLow()
    }
}

A type implementing Repository will get the default implementation of sync(). They could still provide a specialized implementation. However, the type will not be able to use the default Repository.sync in the specialization.

Comments