1

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

2 Answers 2

2

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.

9
  • Interesting, keys are hash-able but it does not mean they are Comparable? right? also I want use map. not keys!
    – user14890475
    Jan 3, 2021 at 7:13
  • 2
    @mimi: Yes. Hashable requires Equatable, but not Comparable.
    – Martin R
    Jan 3, 2021 at 7:14
  • 1
    @mimi: That would be return self.map { $0.key }.sorted(by: <) but I do not see any advantage.
    – Martin R
    Jan 3, 2021 at 7:17
  • I do not know guts of keys, but I am sure apple use map for that as well like me
    – user14890475
    Jan 3, 2021 at 7:19
  • 2
    @mimi: Sure: var sortedKeys: [Key] { keys.sorted() }
    – Martin R
    Jan 3, 2021 at 7:34
1

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.

1
  • I know that, i want write an extension. thanks for help
    – user14890475
    Jan 3, 2021 at 7:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy