Search code examples
iosswiftprotocolsswift-protocolsprotocol-oriented

Swift different default implementations for protocol property


I know that you can give a default value with a protocol extension like this

protocol SomeProtocol {
    var prop: String { get }
}

extension SomeProtocol {
    var prop: String {
        return "defaultValue"
    }
}

struct SomeA: SomeProtocol {}
struct SomeB: SomeProtocol {}

let a = SomeA()
let b = SomeB()

debugPrint(a.prop) // prints defaultValue
debugPrint(b.prop) // prints defaultValue

but is there a way to have different default value for different implementations of the protocol like this without implementing the property for every class or struct that conforms to this protocol?

debugPrint(a.prop) // prints defaultValue
debugPrint(b.prop) // prints differentDefaultValue

or some similar pattern for doing something like this?


Solution

  • Protocol inheritance.

    protocol 😺: SomeProtocol { }
    
    extension 😺 {
      var prop: String { "😺" }
    }
    
    struct SomeA: SomeProtocol { }
    struct SomeB: 😺 { }
    struct SomeC: 😺 { }
    
    SomeA().prop // "defaultValue"
    SomeB().prop // "😺"
    SomeC().prop // "😺"