[英]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.