【发布时间】:2016-11-05 22:06:25
【问题描述】:
我从 Swift 3.0.1 收到一个编译器错误,这让我很困惑。该错误表明计算属性的类型存在歧义,但我不知道如何。
我有一个协议Generic 和一个属性root。该协议有一个通用约束,即root 必须是Root 类型的子类。
class Root { }
protocol Generic {
associatedtype RootType: Root
var root: RootType { get }
}
然后我定义了一个协议扩展,它声明:
如果
Generic是Root的子类,则从root属性返回self。
所以基本上:如果它已经是Root,你可以转发self。
extension Generic where Self: Root {
var root: Self {
return self
}
}
我还有一个GenericWrapper 类,它是Root 的子类,并包装了Generic 的一个实例(使用Generic 代理执行Root 操作)。
class GenericWrapper<T: Generic>: Root {
var generic: T
init(generic: T) {
self.generic = generic
}
}
最后,我定义了一个Specialised 协议,并对其进行了扩展,声明如下:
如果
Specialised实现Generic,则从root属性返回GenericWrapper。
protocol Specialised { }
extension Specialised where Self: Generic {
var root: GenericWrapper<Self> {
get {
return GenericWrapper(generic: self)
}
}
}
然后,当我尝试实现一个实现 Generic 和 Specialised 的类时,我收到了这个错误。
class SpecialisedImplementation: Generic, Specialised {
// errors:
// Ambiguous inference of associated type 'RootType': 'GenericWrapper<SpecialisedImplementation>' vs. 'SpecialisedImplementation'
// Matching requirement 'root' to this declaration inferred associated type to 'GenericWrapper<SpecialisedImplementation>'
// Matching requirement 'root' to this declaration inferred associated type to 'SpecialisedImplementation'
}
我感到困惑的原因是,当Generic: Root 时,SpecialisedImplementation 类与扩展名到Generic 的要求相匹配,但SpecialisedImplementation 不继承自Root 所以它应该不一定?
【问题讨论】:
-
我为此打开了一个错误:bugs.swift.org/browse/SR-3145