最新消息:20210917 已从crifan.com换到crifan.org

[已解决]swift中实现包含某个属性的协议

iOS crifan 2245浏览 0评论

想要实现一个协议,包含了一个属性

其它的类,要符合这个协议,表示就有对应属性变量了

用于传入一个可选择的列表中,把name(或title)属性,用来显示列表的值

但是去写:

protocol NamePrototol {
    var name:String
}

出错:

DropDownTextField.swift:20:9: Property in protocol must have explicit { get } or { get set } specifier

swift property protocol

Swift: setting an optional property of a protocol – Stack Overflow

Optional Computed Properties in Swift Protocols — Matthew Palmer

Protocols in Swift — Coding Explorer Blog

ios – Swift Property that conforms to a Protocol and Class – Stack Overflow

然后去实现:

protocol NameProtocol {
//    var name:String { get set } //get set means read and writable
    var name:String { get } //get means read-only
}
class UserRoleItem: NameProtocol {
    var id:String
    var name:String
    init(id:String = "", name:String = "") {
        self.id = id
        self.name = name
    }
}

即可。

转载请注明:在路上 » [已解决]swift中实现包含某个属性的协议

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
93 queries in 0.183 seconds, using 23.37MB memory