繁体   English   中英

如何将集合的 Swift 扩展限制为泛型类型?

[英]How to restrict a Swift extension of a collection to a generic type?

因为元组在 Swift 中不可散列,所以我创建了一个通用的 struct Couple 来包含两个元素,这些元素组合起来可以用作字典的键。

struct Couple<U: Hashable, V: Hashable>: Hashable {
    let u: U
    let v: V

    init( _ u: U, _ v: V ) {
        self.u = u
        self.v = v
    }
}
var dictionary: [ Couple<Int,Int> : Any ] = ...

现在,我想一般使用 Couple 来扩展 Dictionary。

extension Dictionary where Key == Couple<U: Hashable, V: Hashable>, Value == Any {
    func exampleConvertToArray() -> [ ( U, V, Any ) ] {
    }
}

无论我如何在扩展语句中引用 Couple、U、V,编译器都会抱怨。 如果我改为将泛型添加到函数定义中,编译器也会抱怨。

如果类型不是通用的( extension Dictionary where Key == Couple<Int, Int>, Value == Any ),一切都很好。

如何创建这个通用扩展?

这是可能的,但不幸的是,必须在成员本身而不是整个extension上表达通用约束:

struct Couple<U: Hashable, V: Hashable>: Hashable {
    let u: U
    let v: V

    init( _ u: U, _ v: V ) {
        self.u = u
        self.v = v
    }
}

extension Dictionary {
    func exampleConvertToArray<U, V>() -> [(U, V, Any)] where Key == Couple<U, V> {
        self.map { (key, value) in (key.u, key.v, value) }
    }
}

let input = [
    Couple(1, 2): 3,
    Couple(4, 5): 6,
    Couple(7, 8): 9,
]

let result = input.exampleConvertToArray()
print(result)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM