gpt4 book ai didi

ios - 与隐式解包选项的协议(protocol)一致性

转载 作者:行者123 更新时间:2023-12-01 15:20:14 26 4
gpt4 key购买 nike

我正在尝试制作一个可以在 UILabel 上使用的 Swift 协议(protocol), UITextField , 和 UITextView包含他们的text , attributedText , 和 font特性。
然而,不幸的是,这三个类与它们是使用这些属性的可选类型还是隐式展开的可选类型不一致。
例如,如果我创建此协议(protocol):

protocol MyProtocol: class {
var font: UIFont? { get set }
}
我应用它:
extension UILabel: MyProtocol { }
extension UITextField: MyProtocol { }
extension UITextView: MyProtocol { }
它适用于 UITextFieldUITextView但是 UILabelfont属性是 UIFont!所以编译器说 UILabel不符合 MyProtocol .
另外 textattributedText对于 String? 是可选的 ( UILabel )和 UITextField但为 UITextView 隐式展开( String!)。因此,对于所有三个属性,哪些使用可选项以及哪些使用隐式展开的选项甚至都不一致。
所以我不得不重命名 font在协议(protocol)中,例如。 uiFont本质上是 font 的别名在上面的每个扩展中都有以下实现:
extension UILabel: MyProtocol {
var uiFont: UIFont? {
get { font }
set { font = newValue }
}
}
// … and similarly for UITextField and UITextView
这有点烦人,因为它剥夺了协议(protocol)的简单性。
我找到了 this post on the Swift forum这似乎是同一个问题,讨论似乎说这不是它在 Swift 4.2 中应该表现的方式,但我正在使用 Swift 5 并且仍然得到这个。甚至还有一个 proposal to abolish IUOs得到 merged .
注意我在 macOS Catalina 10.15.6 (19G2021) 上使用 Xcode 11.7 和 iOS 13.7。
有什么方法可以完全避免这个问题,或者让代码更简洁一些,这样我就不需要那么多冗余了?
谢谢

最佳答案

尽管它看起来像是 Swift 中的一个错误,但您可以扩展协议(protocol)本身以使其工作:

extension UILabel: MyProtocol { }
extension MyProtocol where Self: UILabel {
var font: UIFont? {
get { self.font ?? nil }
set { self.font = newValue }
}
}

关于ios - 与隐式解包选项的协议(protocol)一致性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63732801/

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