Swift中具有新泛型的泛型扩展

时间:2019-11-02 14:51:43

标签: swift generics class-extensions

我想通过对Array<Element>的约束来扩展泛型类型Element,该约束依赖于另一泛型类型,例如Element == Optional<Wrapped>

Element不是通用的情况下,这很容易:

extension Array where Element == String {
    func merge() -> String { ... }
}

我尝试了以下操作,但编译器不接受。

extension Array<Wrapped> where Element == Optional<Wrapped> {
    func merge() -> Optional<Wrapped> { ... }
}

在这种情况下应该使用什么语法? 预先感谢!

1 个答案:

答案 0 :(得分:1)

您可以在方法上施加约束:

prime(60)
[2, 3, 5, 7, 9, 11, 11, 13, 13, 15, 17, 17, 17, 19, 19, 19, 21, 23, 23, 23, 25, 25, 25, 27, 29, 29, 29, 29, 31, 31, 31, 31, 33, 35, 35, 35, 37, 37, 37, 37, 37, 39, 41, 41, 41, 41, 41, 43, 43, 43, 43, 43, 45, 47, 47, 47, 47, 47, 49, 49, 49, 49, 49, 51, 53, 53, 53, 53, 53, 53, 55, 55, 55, 57, 59, 59, 59, 59, 59, 59]