Swift different default implementations for protocol property

229 Views Asked by At

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?

1

There are 1 best solutions below

4
On BEST ANSWER

Protocol inheritance.

protocol : SomeProtocol { }

extension  {
  var prop: String { "" }
}

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

SomeA().prop // "defaultValue"
SomeB().prop // ""
SomeC().prop // ""