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



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

我试过这个:

func myFunc(type: CustomStringConvertible.Type & RawRepresentable.Type, rawValue: Int)

导致3个错误:

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

暂时忘记了"CustomStringConvertible",我也尝试过:

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

但是,尽管代码完成表明了这一点,却导致了关于T.init(rawValue:):的错误

  • 无法使用类型为"(rawValue:Int("的参数列表调用"init">

如何形成这样一个可工作的泛型函数?

问题是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)
}

最新更新