Michael
Michael

Reputation: 3

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?

Upvotes: 0

Views: 227

Answers (1)

user652038
user652038

Reputation:

Protocol inheritance.

protocol 😺: SomeProtocol { }

extension 😺 {
  var prop: String { "😺" }
}

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

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

Upvotes: 1

Related Questions