如何在Swift中扩展提取字典的键?
我正在编写这段代码,以生成一个用于生成键数组的扩展,但我无法为数组指定泛型类型,我应该如何修复如何在Swift中扩展提取字典的键?,swift,Swift,我正在编写这段代码,以生成一个用于生成键数组的扩展,但我无法为数组指定泛型类型,我应该如何修复 extension Dictionary { func extractKeys() -> Array<T> { return self.map({ $0.key }).sorted(by: { $0 < $1 } ) } } 扩展字典{ func extractKeys()->数组{ 返回self.map({$0.
extension Dictionary {
func extractKeys() -> Array<T> {
return self.map({ $0.key }).sorted(by: { $0 < $1 } )
}
}
扩展字典{
func extractKeys()->数组{
返回self.map({$0.key}).sorted(按:{$0<$1})
}
}
更新:
extension Dictionary {
var extractSortedKeysV2: [Key] where Key: Comparable {
return self.map({ $0.key }).sorted(by: { $0 < $1 } )
}
}
扩展字典{
var ExtractSortSortedKeySV2:[键]其中键:可比较{
返回self.map({$0.key}).sorted(按:{$0<$1})
}
}
struct Dictionary
是一种通用类型,其中Key
是键的类型,Value
是值的类型。所以您需要返回数组
(或者只返回[Key]
)
此外,为了对密钥进行排序,您必须要求密钥
符合可比
协议:
extension Dictionary where Key: Comparable {
func sortedKeys() -> [Key] {
return self.map({ $0.key }).sorted(by: { $0 < $1 } )
}
}
或作为计算属性:
extension Dictionary where Key: Comparable {
var sortedKeys: [Key] { keys.sorted() }
}
对于函数/方法,可以将约束附加到函数声明:
extension Dictionary {
func sortedKeys() -> [Key] where Key: Comparable {
keys.sorted()
}
}
这在计算属性中是不可能的。struct Dictionary
是一种泛型类型,其中Key
是键的类型,Value
是值的类型。所以您需要返回数组
(或者只返回[Key]
)
此外,为了对密钥进行排序,您必须要求密钥
符合可比
协议:
extension Dictionary where Key: Comparable {
func sortedKeys() -> [Key] {
return self.map({ $0.key }).sorted(by: { $0 < $1 } )
}
}
或作为计算属性:
extension Dictionary where Key: Comparable {
var sortedKeys: [Key] { keys.sorted() }
}
对于函数/方法,可以将约束附加到函数声明:
extension Dictionary {
func sortedKeys() -> [Key] where Key: Comparable {
keys.sorted()
}
}
这在计算属性中是不可能的。没有必要自己做。
字典
中有一个名为的属性,它的作用类似于数组,包含您期望从数组中获得的所有功能,包括排序。无需自己完成。Dictionary
中有一个名为的属性,它的行为类似于数组,包含数组中所需的所有功能,包括排序。我知道,我想编写一个扩展。谢谢你的帮助我知道,我想写一个扩展。感谢您的帮助有趣的是,密钥可以散列,但这并不意味着它们是可比较的?正当我还想用地图。不是钥匙@咪咪:是的。Hashable要求相等,但不可比较。我想与map@mimi:这将是return self.map{$0.key}.sorted(按:@mimi:Sure:var sortedKeys:[key]{keys.sorted()}
有趣的是,键是可哈希的,但这并不意味着它们是可比较的?对吗?我还想使用map。而不是键!@mimi:是的。可哈希要求相等,但不可比较。我想使用map@mimi:这将是return self.map{$0.key}.sorted(按:@mimi:Sure:var sortedKeys:[key]{keys.sorted()}