Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class With Non-Optional Property Conforming To Protocol With Optional Property

Tags:

swift

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
}
like image 859
AnthonyMDev Avatar asked Oct 13 '15 22:10

AnthonyMDev


1 Answers

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
            }
        }
    }
}
like image 186
Ronald Martin Avatar answered Oct 06 '22 21:10

Ronald Martin