If I have a protocol that has an optional property, and a class that needs to conform to the protocol which has the same property already, but as a non-optional property, how do I make the class conform to the protocol.
protocol MyProtocol {
var a: String? { get set }
}
class MyClass {
var a: String
}
extension MyClass: MyProtocol {
// What do I put here to make the class conform
}
Unfortunately, you can't redeclare the same variable in MyClass
with a different type.
What Dennis suggests will work, but if you want to keep your variable in MyClass
non-Optional, then you could use a computed property to wrap around your stored variable:
protocol MyProtocol {
var a: String? { get set }
}
class MyClass {
// Must use a different identifier than 'a'
// Otherwise, "Invalid redeclaration of 'a'" error
var b: String
}
extension MyClass: MyProtocol {
var a: String? {
get {
return b
}
set {
if let newValue = newValue {
b = newValue
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With