如何使用组合类型 CustomStringConvertible 和 RawRepresentable 指定函数参数的类型?

mea*_*ers 1 generics ios swift rawrepresentable

enum我想要一个通用函数,它可以通过提供枚举类型和Int原始值来实例化我拥有的几种不同类型的对象。这些enum也是CustomStringConvertible

我试过这个:

func myFunc(type: CustomStringConvertible.Type & RawRepresentable.Type, rawValue: Int)
Run Code Online (Sandbox Code Playgroud)

这会导致 3 个错误:

  • 非协议、非类类型“CustomStringConvertible.Type”不能在协议约束类型中使用
  • 非协议、非类类型“RawRepresentable.Type”不能在协议约束类型中使用
  • 协议“RawRepresentable”只能用作通用约束,因为它具有 Self 或关联的类型要求

现在忘记“CustomStringConvertible”,我也尝试过:

private func myFunc<T: RawRepresentable>(rawValue: Int, skipList: [T]) {
    let thing = T.init(rawValue: rawValue)
}
Run Code Online (Sandbox Code Playgroud)

但是,尽管代码完成建议这样做,但会导致以下错误T.init(rawValue:)

  • 无法使用类型为“(rawValue: Int)”的参数列表调用“init”

我怎样才能形成这样一个有效的通用函数?

Dáv*_*tor 5

问题在于,这可能与当前的类型限制T.RawValue不同。Int您需要指定这一点T.RawValue == Int才能将您的rawValue: Int输入参数传递给init(rawValue:).

func myFunc<T: RawRepresentable & CustomStringConvertible>(rawValue: Int, skipList: [T]) where T.RawValue == Int {
    let thing = T.init(rawValue: rawValue)
}
Run Code Online (Sandbox Code Playgroud)