我正面临着一个恼人的问题而我正在跳跃,你们可以帮助我。
我有两个协议和一个类:
protocol Prot1: AnyObject {
}
protocol Prot2 {
associatedtype T: AnyObject
}
class TheClass: Prot2 {
typealias T = Prot1
}
这会导致编译器说:
在导航中显示更多详细信息:
我真的需要关联的类型是 AnyObject 类型。这就是我需要帮助的原因。
有谁知道如何解决这个问题?
非常感谢。
OBS:我使用的是swift 2.3
答案 0 :(得分:3)
为了展示你在这里可以做的事情的性质,我将稍微简化一下这个例子。这是合法的:
protocol Prot {
associatedtype T: AnyObject
}
class TheClass: Prot {
typealias T = AnyObject // fine
}
这也是合法的:
protocol Prot {
associatedtype T: AnyObject
}
class TheClass: Prot {
typealias T = NSObject // fine
}
那是因为NSObject是AnyObject的采用者的类型。
但是这(你想要做的)是不合法:
protocol Prot {
associatedtype T: AnyObject
}
protocol SecondProt : AnyObject {
}
class TheClass: Prot {
typealias T = SecondProt // error
}
原因是SecondProt是另一个采用AnyObject的协议。这不是typealias T
插槽中的内容。
这与AnyObject的特殊性质无关。我们可以在没有任何地方提到AnyObject的情况下得到相同的错误:
protocol P {}
protocol Prot {
associatedtype T: P
}
protocol SecondProt : P {
}
class TheClass: Prot {
typealias T = SecondProt // error
}
同样,如果我们提供采用P的类型,我们很好:
protocol P {}
protocol Prot {
associatedtype T: P
}
struct S : P {
}
class TheClass: Prot {
typealias T = S // fine
}
答案 1 :(得分:0)
将Anyobject更改为Any是正常的,或删除Anyobject。 Anyobject是类类型。Type Casting for Any and AnyObject
答案 2 :(得分:0)
此代码段编译。但我不确定这是不是你要找的......
publicPath