![](/img/trans.png)
[英]How to make a constrained extension of Collection generic in 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.