协议中的可选变量是可能的吗?

Ren*_*dey 20 protocols swift

protocol AProtocol: BProtocol {
    /// content to be shown on disclaimer Label of cell
    var disclaimer: String {get set}
    var cellDisclaimerAttributed: NSAttributedString {get}
    var showSelection: Bool {get set}
    var isReadMore: Bool {get}
}
Run Code Online (Sandbox Code Playgroud)

我想让变量成为可选的,这样我就不需要在符合协议后每次都实现所有变量.就像Objective-C一样,我们为方法做了:

protocol AProtocol: BProtocol {
    /// content to be shown on disclaimer Label of cell
    optional var disclaimer: String {get set}
    optional var cellDisclaimerAttributed: NSAttributedString {get}
    optional var showSelection: Bool {get set}
    optional var isReadMore: Bool {get}
}
Run Code Online (Sandbox Code Playgroud)

可能吗?

Ren*_*dey 27

protocol TestProtocol {
    var name : String {set get}
    var age : Int {set get}
}
Run Code Online (Sandbox Code Playgroud)

提供协议的默认扩展名.为所有变量集提供默认实现,并获取您希望它们是可选的.

在以下协议中,名称和年龄是可选的.

 extension TestProtocol {

    var name: String {
        get { return "Any default Name" } set {}
    }  
    var age : Int { get{ return 23 } set{} }      
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我符合上述协议,任何其他类,如

class TestViewController: UIViewController, TestProtocol{
        var itemName: String = ""

**I can implement the name only, and my objective is achieved here, that the controller will not give a warning that "TestViewController does not conform to protocol TestProtocol"**

   var name: String {
        get {
            return itemName ?? ""
        } set {}
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,在`TestViewController`中,您不需要实现`get set`.将变量定义为`var itemName:String =""`就是所需要的. (3认同)
  • 当心!在这个解决方案中,`name`和`age`不能从实例中更改,例如:设置`testVC.age = 30`后,`age`仍然是23! (3认同)

Ale*_* G. 10

如果你想遵守 Swift 的文档,你必须像这样实现:

@objc protocol Named {
    // variables
    var name: String { get }
    @objc optional var age: Int { get }
  
    // methods
    func addTen(to number: Int) -> Int
    @objc optional func addTwenty(to number: Int) -> Int
}

class Person: Named {
    var name: String
    
    init(name: String) {
        self.name = name
    }
    
    func addTen(to number: Int) -> Int {
        return number + 10
    }
}
Run Code Online (Sandbox Code Playgroud)