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/