Reputation: 3023
I want to convert below code into swift, Actually i want do not want to loose order of keys using allKeys of nsdictionary
NSArray *keys = [myDictionary allKeys];
keys = [keys sortedArrayUsingComparator:^(id a, id b) {
return [a compare:b options:NSNumericSearch];
}];
Upvotes: 1
Views: 1377
Reputation: 1359
For Swift 3.0 version
let myDictionary = ["100" : "foo", "2" : "bar"]
let keys = self.myDictionary.allKeys.sorted {
($0 as AnyObject).compare($1 as! String, options: .numeric) == .orderedDescending
}
print(keys) // ["2", "100"]
.orderedDescending
is used to sort the array in descending order where as .orderedAscending
is used to sort the array in ascending order.
Upvotes: 0
Reputation: 539745
You can do the same in Swift:
let myDictionary = ["100" : "foo", "2" : "bar"]
let keys = myDictionary.keys.sort {
$0.compare($1, options: .NumericSearch) == .OrderedAscending
}
print(keys) // ["2", "100"]
myDictionary.keys
gives a (lazy collection) of all the dictionary
keys and can be sorted. In contrast to
sortedArrayUsingComparator
(which takes a block returning -1
, 0
,
or +1
), the sort()
method takes a closure returning
a boolean value which is true
if the lhs is "smaller" than the
rhs.
Upvotes: 1