将具有多个泛型类型的枚举作为参数传递

Passing enum with multiple generic types as argument

我遇到 Swift 2 - XCode 版本 7.0 beta 5 (7A176x)

的问题

我有一个具有两个通用类型的枚举状态。函数 printState 接受一个 State 参数并根据参数

打印 "One" 或 "Two"
protocol Protocol1 {
}

struct Struct1: Protocol1 {
}

protocol Protocol2 {
}

struct Struct2: Protocol2 {
}

enum State<T:Protocol1, U:Protocol2> {
  case One(firstStruct: T, secondStruct:U)
  case Two(secondStruct:U)
}

func printState<T:Protocol1, U:Protocol2>(state: State<T,U>) {
  switch state {
  case .One( _):
    print("One")
  case .Two( _):
    print("Two")
  }
}

当我如下调用 printState 时。

printState(State.One(firstStruct:Struct1(), secondStruct:Struct2()))
printState(State.Two(secondStruct:Struct2())) // This fails on compilation

第二次调用 printState 时出现编译错误 -

error: cannot invoke 'Two' with an argument list of type '(secondStruct: Struct2)' printState(State.Two(secondStruct:Struct2()))

如果 T 和 U 被限制为 class 类型,一切正常。但只有当 T 和 U 是协议类型时,我才会收到此错误。另外,我可以通过使案例二也接受 Protocol1 来消除这个错误,但它并不真的需要它。

为什么会出现此错误?我怎样才能使这个工作,以便案例二只接受 Protocol1。

问题是编译器无法推断 T 的类型,因为您只指定了 U 的类型。因此,您必须明确定义类型:

printState(State<Struct1, Struct2>.Two(secondStruct:Struct2()))