您的IdentifierProtocol
是RawRepresentable
,它有associatedType
。而且这种协议不能用于“如果它是具体类型”。
这基本上是编译错误说什么:
error: protocol 'A_IdentifierProtocol' can only be used as a generic constraint because it has Self or associated type requirements
,而不是复制的信息,我建议你阅读你所得到的错误,这样的解释:https://stackoverflow.com/a/36350283/2378431
如果你想解决这个错误,仍然让你的代码在没有任何明显区别的情况下工作(从使用的角度来看),你可以为每个X_IdentifierProtocol
定义单一方法,如下所示:
protocol IdentifierProtocol: Equatable, RawRepresentable {}
protocol A_IdentifierProtocol: IdentifierProtocol {}
protocol B_IdentifierProtocol: IdentifierProtocol {}
func myFunc<I: A_IdentifierProtocol>(identifier: I) where I.RawValue == String {
print("A: \(identifier.rawValue)")
}
func myFunc<I: B_IdentifierProtocol>(identifier: I) where I.RawValue == String {
print("B: \(identifier.rawValue)")
}
的缺点是,每X_IdentifierProtocol
你需要提供一个方法的实现,并可能引入一些重复代码,如果你想拥有一张基于IdentifierProtocol
共享代码。
另一种方法:如果您确实需要单功能,则不能使用IdentifierProtocol
和关联类型。但是你可以在通用功能的多个类型的限制,这样的事情:
protocol IdentifierProtocol {}
protocol A_IdentifierProtocol: IdentifierProtocol {}
protocol B_IdentifierProtocol: IdentifierProtocol {}
func myFunc<I: IdentifierProtocol & Equatable & RawRepresentable>(identifier: I) where I.RawValue == String {
if identifier is A_IdentifierProtocol {
print("A: \(identifier.rawValue)")
}
if identifier is B_IdentifierProtocol {
print("A: \(identifier.rawValue)")
}
}
class MyClassA: A_IdentifierProtocol, RawRepresentable, Equatable {...}
class MyClassB: B_IdentifierProtocol, RawRepresentable, Equatable {...}
但是即使有这是完美的,没有全覆盖您的要求。
底线是,你不能达到你想要什么用斯威夫特3.
那么什么是你的错误? – Tali