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 // "๐Ÿ˜บ"