简体   繁体   中英

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. So you'll want to return Array<Key> (or just [Key] ).

In addition, in order to sort the keys, you have to require that Key conforms to the Comparable protocol:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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