具有非可选属性的类符合具有可选属性的协议

Ant*_*Dev 5 swift

如果我有一个具有可选属性的协议,以及一个需要符合具有相同属性的协议的类,但作为非可选属性,我该如何使该类符合该协议.

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
}
Run Code Online (Sandbox Code Playgroud)

Ron*_*tin 5

不幸的是,您无法MyClass使用其他类型重新声明相同的变量.

Dennis建议使用什么,但是如果你想将变量保存在MyClass非Optional中,那么你可以使用一个computed属性来包装你存储的变量:

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
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)