简体   繁体   English

如何进行扩展以提取 Swift 中的字典键?

[英]How can I make an extension for extracting keys of a Dictionary in Swift?

I am working on this code for making a extension for making key array, but I am unable to give generic type to my array, what I should do for fixing?我正在编写此代码来制作用于制作键数组的扩展,但我无法为我的数组提供泛型类型,我应该怎么做才能修复?

    extension Dictionary {

    func extractKeys() -> Array<T>  {
        
       return self.map({ $0.key }).sorted(by: { $0 < $1 } )
    }

}

update:更新:

extension Dictionary {
    
    var extractSortedKeysV2: [Key] where Key: Comparable {
        
        return self.map({ $0.key }).sorted(by: { $0 < $1 } )
        
    }
 
}

struct Dictionary<Key, Value> is a generic type where Key is the type of the keys, and Value the type of the values. struct Dictionary<Key, Value>是一个泛型类型,其中Key是键的类型, Value是值的类型。 So you'll want to return Array<Key> (or just [Key] ).所以你会想要返回Array<Key> (或者只是[Key] )。

In addition, in order to sort the keys, you have to require that Key conforms to the Comparable protocol:此外,为了对键进行排序,您必须要求Key符合Comparable协议:

extension Dictionary where Key: Comparable {
    func sortedKeys() -> [Key]  {
        return self.map({ $0.key }).sorted(by: { $0 < $1 } )
    }
}

This can be simplified to这可以简化为

extension Dictionary where Key: Comparable {
    func sortedKeys() -> [Key]  {
        keys.sorted()
    }
}

Or as a computed property:或作为计算属性:

extension Dictionary where Key: Comparable {
    var sortedKeys: [Key] { keys.sorted() }
}

In the case of the function/method, the constraint can be attached to the function declaration instead:在函数/方法的情况下,可以将约束附加到 function 声明中:

extension Dictionary {
    func sortedKeys() -> [Key] where Key: Comparable {
        keys.sorted()
    }
}

That is not possible with computed properties.这对于计算属性是不可能的。

There's no need to do it yourself.没有必要自己做。 There's a property in Dictionary calledkeys that act like an array and contain all the functionality you expect from an array including sorting. Dictionary中有一个称为keys的属性,它的作用类似于数组,包含您期望从数组中获得的所有功能,包括排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM