Reputation:
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
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