Swift:设置协议的可选属性

前端之家收集整理的这篇文章主要介绍了Swift:设置协议的可选属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何设置协议的可选属性?例如,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.

猜你在找的Swift相关文章