[英]How can I make an extension for extracting keys of a Dictionary in Swift?
我正在編寫此代碼來制作用於制作鍵數組的擴展,但我無法為我的數組提供泛型類型,我應該怎么做才能修復?
extension Dictionary {
func extractKeys() -> Array<T> {
return self.map({ $0.key }).sorted(by: { $0 < $1 } )
}
}
更新:
extension Dictionary {
var extractSortedKeysV2: [Key] where Key: Comparable {
return self.map({ $0.key }).sorted(by: { $0 < $1 } )
}
}
struct Dictionary<Key, Value>
是一個泛型類型,其中Key
是鍵的類型, Value
是值的類型。 所以你會想要返回Array<Key>
(或者只是[Key]
)。
此外,為了對鍵進行排序,您必須要求Key
符合Comparable
協議:
extension Dictionary where Key: Comparable {
func sortedKeys() -> [Key] {
return self.map({ $0.key }).sorted(by: { $0 < $1 } )
}
}
這可以簡化為
extension Dictionary where Key: Comparable {
func sortedKeys() -> [Key] {
keys.sorted()
}
}
或作為計算屬性:
extension Dictionary where Key: Comparable {
var sortedKeys: [Key] { keys.sorted() }
}
在函數/方法的情況下,可以將約束附加到 function 聲明中:
extension Dictionary {
func sortedKeys() -> [Key] where Key: Comparable {
keys.sorted()
}
}
這對於計算屬性是不可能的。
沒有必要自己做。 Dictionary
中有一個稱為keys
的屬性,它的作用類似於數組,包含您期望從數組中獲得的所有功能,包括排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.