Swift 为什么纯类协议在协议扩展where子句中不满足AnyObject约束?
我定义了协议:Swift 为什么纯类协议在协议扩展where子句中不满足AnyObject约束?,swift,inheritance,Swift,Inheritance,我定义了协议: protocol MyProtocol: class { } class MyClass: MyProtocol { } extension CollectionType where Generator.Element : First { func someFunc() { } } protocol First { } protocol Second: First { } var items = [Second]() items.someFun
protocol MyProtocol: class {
}
class MyClass: MyProtocol {
}
extension CollectionType where Generator.Element : First {
func someFunc() {
}
}
protocol First {
}
protocol Second: First {
}
var items = [Second]()
items.someFunc() // Type 'Second' does not conform to protocol 'First'
和扩展仅适用于具有类元素的集合:
extension CollectionType where Generator.Element: class {
func someFunc() {
}
}
var items = [MyClass]()
items.someFunc() // someFunc is available
var strings = [String]()
// strings.someFunc() is not available because String is not class
但这不会编译,我将扩展定义更改为:
extension CollectionType where Generator.Element: AnyObject {
...
}
它也不会编译,因为MyProtocol不符合AnyObject。
因此,我将MyProtocol的定义更改为:
它也不使用以下消息编译:
类型“MyProtocol”不符合协议“AnyObject”
经过一点研究,我发现协议类型不符合协议:
protocol MyProtocol: class {
}
class MyClass: MyProtocol {
}
extension CollectionType where Generator.Element : First {
func someFunc() {
}
}
protocol First {
}
protocol Second: First {
}
var items = [Second]()
items.someFunc() // Type 'Second' does not conform to protocol 'First'
因此,在我的例子中,真正的问题不是仅类协议不满足AnyObject约束,而是协议类型不能符合AnyObject协议或任何其他协议。扩展数组,其中Element:AnyObject{}为我编译。但这和我的协议有什么关系?@MartinR抱歉,我更新了问题的更多细节。扩展收集是什么意思?你是说收藏类型吗?这是您的真实代码吗???@matt抱歉,我没有从Xcode Playerd复制代码,在键入代码时犯了一个错误。@MartinR是的,这是一个类似的问题,但我找到的答案与纯类协议和从任何对象扩展的协议之间的差异无关。