我正在为扩展密钥数组的扩展编写此代码,但无法为数组提供通用类型,该如何解决?
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() }
}
对于函数/方法,可以将约束附加到函数声明中:
extension Dictionary {
func sortedKeys() -> [Key] where Key: Comparable {
keys.sorted()
}
}
使用计算的属性是不可能的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句