gpt4 book ai didi

Swift:设置协议(protocol)的可选属性

转载 作者:IT王子 更新时间:2023-10-29 05:17:18 26 4
gpt4 key购买 nike

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

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

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

textInputTraits.keyboardType? = .Default

协议(protocol)如下:

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:设置协议(protocol)的可选属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26083377/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com