[英]Type does not conform to protocol - typealias to another protocol
I'm facing an anoying problem and I was hopping that you guys could help me with that. 我面临着一个棘手的问题,我希望你们可以帮助我解决这个问题。
I have two protocols and one class: 我有两个协议和一个类:
protocol Prot1: AnyObject {
}
protocol Prot2 {
associatedtype T: AnyObject
}
class TheClass: Prot2 {
typealias T = Prot1
}
This causes the compiler to say: 这使编译器说:
In the navigation it shows more details: 在导航中,它显示更多详细信息:
I realy need the associated type to be of the AnyObject type. 我确实需要关联类型为AnyObject类型。 This is why I need help.
这就是为什么我需要帮助。
Does anyone know how to solve this? 有谁知道如何解决这个问题?
Thank you very much. 非常感谢你。
OBS: I'm using swift 2.3 OBS:我正在使用Swift 2.3
To show the nature of what you can do here, I will simplify the example slightly. 为了展示您可以在此处执行的操作的性质,我将稍微简化一下示例。 This is legal:
这是合法的:
protocol Prot {
associatedtype T: AnyObject
}
class TheClass: Prot {
typealias T = AnyObject // fine
}
This is also legal: 这也是合法的:
protocol Prot {
associatedtype T: AnyObject
}
class TheClass: Prot {
typealias T = NSObject // fine
}
That's because NSObject is a type that is an adopter of AnyObject. 这是因为NSObject是AnyObject的采用者 。
But this (what you're trying to do) is not legal: 但这(您要尝试执行的操作) 不合法:
protocol Prot {
associatedtype T: AnyObject
}
protocol SecondProt : AnyObject {
}
class TheClass: Prot {
typealias T = SecondProt // error
}
The reason is that SecondProt is another protocol that adopts AnyObject. 原因是SecondProt是采用AnyObject的另一种协议 。 That is not something that can go in the
typealias T
slot. 那不是
typealias T
插槽中可以使用的东西。
This has nothing to do with the special nature of AnyObject. 这与AnyObject的特殊性质无关。 We can get the same error without mentioning AnyObject anywhere:
我们可以在没有任何地方提及AnyObject的情况下得到相同的错误:
protocol P {}
protocol Prot {
associatedtype T: P
}
protocol SecondProt : P {
}
class TheClass: Prot {
typealias T = SecondProt // error
}
Again, if we supply a type that adopts P, we're fine: 同样,如果我们提供采用P的类型 ,则可以:
protocol P {}
protocol Prot {
associatedtype T: P
}
struct S : P {
}
class TheClass: Prot {
typealias T = S // fine
}
Change Anyobject to Any is ok, or delete Anyobject. 可以将Anyobject更改为Any,或删除Anyobject。 Anyobject is class type.
Anyobject是类类型。 Type Casting for Any and AnyObject
类型转换为Any和AnyObject
This snippet compiles. 该代码段编译。 But I am not sure if it's what you're looking for...
但是我不确定这是否是您想要的...
protocol Prot1: AnyObject
{
}
protocol Prot2
{
associatedtype T: AnyObject
}
class TheClass: Prot2
{
typealias U = Prot1
typealias T = AnyObject
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.