我的类可以覆盖 Swift 中的协议属性类型吗? [英] Can my class override protocol property type in Swift?

查看:60
本文介绍了我的类可以覆盖 Swift 中的协议属性类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

protocol Parent {
     var children: [AnyObject] { get set }
}

class Foo {
}

class Bar: Parent { //error happens here
    var children = [Foo]()

    init() {}
}

我收到一个错误类型‘对象’不符合协议‘父’.我收到这个错误的原因是因为我将 children 定义为一个 Foo 数组而不是 AnyObject.有什么办法可以做到这一点工作吗?

I get an error "Type 'Object' does not conform to protocol 'Parent'. The reason I get this error is because I defined children to be an array of Foo rather than AnyObject. Is there any way I can make this work?

推荐答案

在协议中要求 AnyObject 意味着 children 数组 必须 能够接受 AnyObject 条目.但听起来您希望 Bar 的孩子只是 Foo 对象.

Requiring AnyObject in the protocol means the children array must be able to accept AnyObject entries. But it sounds like you want Bar's children to be only Foo objects.

相反,您可以给协议一个 关联类型:

Instead, you can give the protocol an associated type:

protocol Parent {
    associatedtype Child
    var children: [Child] { get set }
}

class Foo { }

class Bar: Parent {
    var children = [Foo]()
    init() {}
}

这篇关于我的类可以覆盖 Swift 中的协议属性类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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