2017-03-22 92 views
0

我有2个协议,从一个普通的协议继承通用协议

protocol IdentifierProtocol: Equatable, RawRepresentable {} 

protocol A_IdentifierProtocol: IdentifierProtocol {} 
protocol B_IdentifierProtocol: IdentifierProtocol {} 

继承和我想用一个函数来拆分,但是这个代码给出了一个错误

extension UIClass { 
    func myFunc<I: IdentifierProtocol>(identifier: I) where I.RawValue == String { 
     if identifier is A_IdentifierProtocol { // <- Error 
      print("A") 
     } 
     if identifier is B_IdentifierProtocol { // <- Error 
      print("B") 
     } 
    } 
} 

error: protocol 'A_IdentifierProtocol' can only be used as a generic constraint because it has Self or associated type requirements

哪有我解决这个问题?

+0

那么什么是你的错误? – Tali

回答

0

您的IdentifierProtocolRawRepresentable,它有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.

+0

我只是想将许多方法合并为一个。我使用通用的基本类型。这是定义associatedType –

+0

看一看,我已经添加了另一种方法,但仍然不完全是你想要的。 AFAIK你无法实现你想要的Swift 3。 –