ios – 类型不符合协议

ios – 类型不符合协议,第1张

概述我仍然无法理解 Swift中泛型的一些微妙之处.我定义了以下类型: protocol SomeProtocol { func setValue(value: Int)}class ProtocolLabel : UILabel, SomeProtocol { func setValue(value: Int) { }}class ProtocolImageVi 我仍然无法理解 Swift中泛型的一些微妙之处.我定义了以下类型:
protocol SomeProtocol {    func setValue(value: Int)}class ProtocolLabel : UILabel,SomeProtocol {    func setValue(value: Int) {    }}class ProtocolimageVIEw : UIImageVIEw,SomeProtocol {    func setValue(value: Int) {    }}

vIEwForValue(2)
现在我定义了以下功能.我希望T是一个符合协议SomeProtocol的UIVIEw.

func vIEwForValue<T where T: SomeProtocol,T: UIVIEw>(param: Int) -> UIVIEw {    var someVIEw: T    if param > 0 {        someVIEw = ProtocolLabel() as T    } else {        someVIEw = ProtocolimageVIEw() as T    }    someVIEw.setValue(2)    someVIEw.frame = CGRectZero    return someVIEw}

但是,当我执行代码时,我收到以下编译错误:

vIEwForValue(2) // <-- Type 'UIVIEw' does not conform to protocol 'SomeProtocol'

似乎在where子句中我不能指定不实现协议的类.这是为什么?

提前致谢.

解决方法 vIEwForValue应该返回一个继承自UIVIEw并实现SomeProtocol的类.
您已经定义了两个没有直接关系的类 – 它们只是从UIVIEw继承并实现SomeProtocol.

当函数必须确定返回类型时,两个类继承的直接具体类型是UIVIEw,这就是vIEwForValue返回的内容.

为了解决这个问题,你必须通过创建一个继承自UIVIEw并实现SomeProtocol的第三类来创建两个类之间的直接和具体的关系:

protocol SomeProtocol {    func setValue(value: Int)}class SomeClass: UIVIEw,SomeProtocol {    func setValue(value: Int) {    }}class SomeSubclass : SomeClass {}class SomeOtherSubclass : SomeClass {}func vIEwForValue<T where T: SomeProtocol,T: SomeClass>(param: Int) -> T {    var someVIEw: T    if param > 0 {        someVIEw = SomeSubclass() as T    } else {        someVIEw = SomeOtherSubclass() as T    }    someVIEw.setValue(2)    someVIEw.frame = CGRectZero    return someVIEw}vIEwForValue(2)

附录:阅读下面的OP评论,目的是动态实例化从UIVIEw继承的现有UIKit类.因此,建议的解决方案不适用.

我认为通过实现SomeProtocol来扩展UIVIEw应该可行:

protocol SomeProtocol {    func setValue(value: Int)}extension UIVIEw : SomeProtocol {    func setValue(value: Int) {    }}func vIEwForValue<T where T: SomeProtocol,T: UIVIEw>(param: Int) -> UIVIEw {    var someVIEw: T    if param > 0 {        someVIEw = UILabel() as T    } else {        someVIEw = UIImageVIEw() as T    }    someVIEw.setValue(2)    someVIEw.frame = CGRectZero    return someVIEw}

但看起来有一个编译器错误. *** 场上的此代码显示一条消息,指出:

Communication with the playground service was interrupted unexpectedly.
The playground service “com.apple.dt.Xcode.Playground” may have generated a crash log.

而在iOS应用程序中,由于分段错误,编译失败11.

总结

以上是内存溢出为你收集整理的ios – 类型不符合协议全部内容,希望文章能够帮你解决ios – 类型不符合协议所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1100542.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存