swift - 协议(protocol)中的可选变量是可能的吗?

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

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

这可能吗?

最佳答案

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

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

在下面的协议(protocol)中,姓名和年龄是可选的。

 extension TestProtocol {

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

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

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

关于swift - 协议(protocol)中的可选变量是可能的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44307238/

相关文章:

xcode - Swift:枚举类型作为属性

objective-c - 协议(protocol)方法的默认值是可选的还是必需的?

objective-c - 实现委托(delegate)和协议(protocol)以在 View 之间传递数据

generics - 快速泛型的段错误

swift - 为 backgroundSession.uploadTask 实现完成处理程序

c++ - 在 C/C++ 中创建和发送原始数据包

ios - 如何映射 json 响应并创建带索引的简单列表

ios - 如何使用 iOS 为 AWS API Gateway (Swift) 生成的开发工具包

ios - 拖放 - 从我的模型创建一个 NSItemProvider

ios - 如何在 swift 中禁用 UIAlertController 的解雇