Swift:设置协议的可选属性 [英] Swift: setting an optional property of a protocol

查看:48
本文介绍了Swift:设置协议的可选属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置协议的可选属性?例如 UITextInputTraits 有许多可选的读/写属性.当我尝试以下操作时,出现编译错误(无法分配给textInputTraits"中的keyboardType"):

How does one set an optional property of a protocol? For example UITextInputTraits has a number of optional read/write properties. When I try the following I get a compile error (Cannot assign to 'keyboardType' in 'textInputTraits'):

func initializeTextInputTraits(textInputTraits: UITextInputTraits) {
  textInputTraits.keyboardType = .Default
}

通常在访问协议的可选属性时会添加问号,但在分配值时不起作用(错误:无法分配给此表达式的结果):

Normally when accessing an optional property of a protocol you add a question mark but this doesn't work when assigning a value (error: Cannot assign to the result of this expression):

textInputTraits.keyboardType? = .Default

协议如下:

protocol UITextInputTraits : NSObjectProtocol {
  optional var keyboardType: UIKeyboardType { get set }
}

推荐答案

这在 Swift 中是不可能的(但是?).引用自 ADF 线程:

It's impossible in Swift (yet?). Referenced from an 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:设置协议的可选属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆