如何编写枚举类型的Swift泛型函数?

时间:2014-08-14 15:29:55

标签: class generics enums swift protocols

使用Swift,我想编写一个协议,指定实现类必须具有一个带枚举的函数(它遵循给定的协议),其中枚举类型通常是指定的。我试过这个:

protocol Message {}

protocol Subscriber {
  func receive<T where T:Message>(message:T)
}

enum Greeting : Message {
  case Hello, Goodbye
}

class SomeObject : Subscriber {
  func receive<Greeting>(message: Greeting) {
    switch message {
    case .Hello:
      println("Hello")
    case .Goodbye:
      println("Goodbye")
    }
  }
}

无法使用“每个案例行中的枚举案例模式无法匹配非枚举类型'Greeting'的值进行编译”。这似乎是因为订阅者协议期望一些不比Message更专业的东西,但我根据Greeting设置,虽然它实现了Message,但它更专业。 (我是对的吗?)

那么,我该如何做我想做的事呢?

1 个答案:

答案 0 :(得分:11)

泛型类型参数TSubscriber的实现中仍应是通用的。 您可以使用typealias中的protocol Subscriber执行您要求的操作,并在其上强制执行Message超类约束:

protocol Message {}

protocol Subscriber {
    typealias MessageType: Message
    func receive (message: MessageType)
}

enum Greeting : Message {
    case Hello, Goodbye
}

class SomeObject : Subscriber {
    typealias MessageType = Greeting

    func receive (message: MessageType) {
        switch message {
        case .Hello:
            println("Hello")
        case .Goodbye:
            println("Goodbye")
        }
    }
}

使用通用receive会阻止您切换enum字段:

protocol Message {}

protocol Subscriber {
    func receive <T: Message> (message: T)
}

enum Greeting : Message {
    case Hello, Goodbye
}

class SomeObject : Subscriber {
    func receive <T: Message> (message: T) {

    }
}

let obj = SomeObject()
obj.receive(Greeting.Hello)
相关问题