代码之家  ›  专栏  ›  技术社区  ›  meaning-matters

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

  •  0
  • meaning-matters  · 技术社区  · 6 年前

    我想要一个泛型函数,可以实例化一些不同的对象 enum Int 枚举 s也是 CustomStringConvertible

    我试过了:

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

    这会导致3个错误:

    • 非协议,非类类型'RawRepresentable.类型'不能在协议约束类型中使用
    • 协议“RawRepresentable”只能用作泛型约束,因为它具有自身或关联的类型要求

    暂时忘记了“CustomStringConvertible”,我还尝试了:

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

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

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

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

    1 回复  |  直到 6 年前
        1
  •  2
  •   Dávid Pásztor    6 年前

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