符合Equatable协议的Cast类泛型

时间:2018-09-20 08:17:41

标签: swift

如何在不声明具体类型的情况下在Swift中强制转换泛型以符合协议?

class SomeModel<T: Equatable> {
    var value: T?
    ...
}

下面的代码产生编译错误:不支持将“ Equatable”用作符合协议“ Equatable”的具体类型

switch model {
case let model as SomeModel<Equatable>:
    someMethod(model)
    break
default:
    break
}

如何处理符合Equatable协议的所有通用类?我认为处理每种类型分离的想法不是很好:

switch model {
case let model as SomeModel<Int>:
    someMethod(model)
    break
case let model as SomeModel<Double>:
    someMethod(model)
    break
case let model as SomeModel<Date>:
    someMethod(model)
    break
...
default:
    break
}

修改1: 添加了方法 someMethod 作为示例来显示模型处理。无论如何,它看起来可能像这样:func someMethod(_ model: SomeModel<Equatable>)。如果无法传递此类参数,则至少进行 switch 强制转换而不调用任何函数或使用不带参数的调用函数就足够了:func someMethod()

修改2: 提供有关该问题的更多信息。类 SomeModel 继承自另一个类 BaseModel ,因此 SomeModel 声明如下:

class SomeModel<T: Equatable>: BaseModel {
    var value: T?
    ...
}

我使用 switch 语句来处理 BaseModel 的不同子类,其中大多数不是通用的。

///Variable `models` here is of a type [BaseModel]
for model in models {
    switch model {
    case let model as SomeModel<Int>:
        someMethod()
        break
    case let model as SomeModel<Double>:
        someMethod()
        break
    case let model as SomeModel<Date>:
        someMethod()
        break
    ...
    case let model as AnotherModel:
        anotherMethod(model)
        break
    default:
        break
    }
}

有什么方法可以合并SomeModel<Int>SomeModel<Double>等?

0 个答案:

没有答案