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

时间:2017-06-01 12:12:50

标签: swift protocols

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}
}

我想让变量成为可选的,这样我就不需要在符合协议后每次都实现所有变量。就像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}
}

有可能吗?

2 个答案:

答案 0 :(得分:18)

protocol TestProtocol {
    var name : String {set get}
    var age : Int {set get}
}

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

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

 extension TestProtocol {

    var name: String {
        get { return "Any default Name" } set {}
    }  
    var age : Int { get{ return 23 } set{} }      
}

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

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 {}
    }
}

答案 1 :(得分:4)

如果你想要conform to Swift's documentation,你应该像这样实现它:

@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
    }
}