Let's say that I have the following protocol:
protocol Identifiable {
var id: Int {get}
var name: String {get}
}
And that I have the following structs:
struct A: Identifiable {
var id: Int
var name: String
}
struct B: Identifiable {
var id: Int
var name: String
}
As you can see, I had to 'conform' to the Identifiable protocol in struct A and struct B. But imagine if I had N more structs that needs to conform to this protocol... I don't want to 'copy/paste' the conformance (var id: Int, var name: String)
So I create a protocol extension:
extension Identifiable {
var id: Int {
return 0
}
var name: String {
return "default"
}
}
With this extension now I can create a struct that conforms to the Identifiable protocol without having to implement both properties:
struct C: Identifiable {
}
Now the problem is that I can't set a value to the id property or the name property:
var c: C = C()
c.id = 12 // Cannot assign to property: 'id' is a get-only property
This happens because in the Identifiable protocol, id and name are only gettable. Now if I change the id and name properties to {get set} I get the following error:
Type 'C' does not conform to protocol 'Identifiable'
This error happens because I haven't implemented a setter in the protocol extension... So I change the protocol extension:
extension Identifiable {
var id: Int {
get {
return 0
}
set {
}
}
var name: String {
get {
return "default"
}
set {
}
}
}
Now the error goes away but if I set a new value to id or name, it gets the default value (getter). Of course, the setter is empty.
My question is:
What piece of code do I have to put inside the setter? Because if I add self.id = newValue it crashes (recursive).
Thanks in advance.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…