user14890475
user14890475

Reputation:

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 } )
        
    }
 
}

Upvotes: 1

Views: 73

Answers (2)

Martin R
Martin R

Reputation: 539815

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.

Upvotes: 2

alobaili
alobaili

Reputation: 904

There's no need to do it yourself. There's a property in Dictionary called keys that act like an array and contain all the functionality you expect from an array including sorting.

Upvotes: 1

Related Questions