什么类型的字符串枚举,所以它可以用作参数?

时间:2016-07-11 18:51:06

标签: swift enums

在我当前的实现中,我使用rawValue将字符串枚举传递给函数,如下所示:

enum Compass: String {
  case North, South, East, West
}

func something(key: String) {...}

something(Compass.East.rawValue)

除了String之外还有其他类型的函数,所以我可以这样做吗?

something(Compass.East)

我不想制作key类型的Compass参数,因为我enums来自不同的地方,但都来自String

我尝试过这样做,但收到了错误:

func something(key:StringLiteralConvertible){...} //错误:协议' StringLiteralConvertible'只能用作通用约束

是否有我可以使用的类型,所以我不必每次都使用rawValue

1 个答案:

答案 0 :(得分:7)

You can do this:

func something<T: RawRepresentable where T.RawValue == String>(key: T) {
    let string = key.rawValue
}

something(Compass.East)

This lets you pass in any enum that has Strings as its values