加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift:设置协议的可选属性

发布时间:2020-12-14 05:36:35 所属栏目:百科 来源:网络整理
导读:如何设置协议的可选属性?例如,UITextInputTraits具有多个可选的读/写属性.当我尝试以下我得到一个编译错误(无法在’textInputTraits’中分配给’keyboardType’): func initializeTextInputTraits(textInputTraits: UITextInputTraits) { textInputTraits.
如何设置协议的可选属性?例如,UITextInputTraits具有多个可选的读/写属性.当我尝试以下我得到一个编译错误(无法在’textInputTraits’中分配给’keyboardType’):
func initializeTextInputTraits(textInputTraits: UITextInputTraits) {
  textInputTraits.keyboardType = .Default
}

通常当访问协议的可选属性时,您添加一个问号,但是在分配值时无效(错误:无法分配给此表达式的结果):

textInputTraits.keyboardType? = .Default

协议如下:

protocol UITextInputTraits : NSObjectProtocol {
  optional var keyboardType: UIKeyboardType { get set }
}
这是不可能的Swift(还是?).从 ADF thread引用:

Optional property requirements,and optional method requirements that return a value,will always return an optional value of the appropriate type when they are accessed or called,to reflect the fact that the optional requirement may not have been implemented.

So it’s no surprise to get optional values easily. However,setting a property requires implementation to be guaranteed.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读