Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting in swift 3.0

var arr:Array<Dictionary<String, String>> = [["title":"Mrs","name":"Abc"],["title":"Mr","name":"XYZ"]]
arr.sort { (<#[String : String]#>, <#[String : String]#>) -> Bool in
        <#code#>
    }

I have an array of dictionaries with the data format as represented above. I want to sort this array by name key. I did it in older swift like:

arr.sort{$0.name < $1.name}

which is not working anymore. Please let me know how to move ahead with this structure and sort it.

Thanks.

like image 230
Madhup Singh Yadav Avatar asked May 09 '26 13:05

Madhup Singh Yadav


2 Answers

You have an array of dictionaries of the form [String: String] and a dictionary does not have a name property, so $0.name is invalid (in any Swift version).

Retrieving the dictionary value is done via subscripting, e.g. $0["name"], which returns an optional. In Swift 2 you could compare optionals directly (and nil was considered "less" than any non-nil value). Therefore in Swift 2 you could sort the array with

arr.sortInPlace { $0["name"] < $1["name"] }

However, the optional comparison operators have been removed in Swift 3 with the implementation of SE-0121 – Remove Optional Comparison Operators.

Therefore you have to unwrap $0["name"]. If you are 100% sure that every dictionary in the array has a "name" key then you can unwrap forcefully as Ahmad F suggested

arr.sort { $0["name"]! < $1["name"]! }

If that is not guaranteed then provide a default name, e.g. the empty string via the nil-coalescing operator ??:

arr.sort { ($0["name"] ?? "") < ($1["name"] ?? "") }

Example:

var arr = [["title":"Mrs","name":"Abc"], ["title":"Mr","name":"XYZ"], ["title": "Dr"]]
arr.sort { ($0["name"] ?? "") < ($1["name"] ?? "") }
print(arr)
// [["title": "Dr"], ["name": "Abc", "title": "Mrs"], ["name": "XYZ", "title": "Mr"]]

As one can see, the dictionary without a "name" key is ordered first. A simple way to sort entries without name last would be:

arr.sort { ($0["name"] ?? "\u{10FFFF}") < ($1["name"] ?? "\u{10FFFF}") }
like image 164
Martin R Avatar answered May 12 '26 05:05

Martin R


Actually, I'm not pretty sure if arr.sort{$0.name < $1.name} worked in "older swift", however, it should be like:

var arr:Array<Dictionary<String, String>> = [["title":"Mr","name":"XYZ"], ["title":"Mrs","name":"Abc"]]

print(arr) // [["name": "XYZ", "title": "Mr"], ["name": "Abc", "title": "Mrs"]]

arr.sort {
    ($0["name"])! < ($1["name"])!
}

print(arr) // [["name": "Abc", "title": "Mrs"], ["name": "XYZ", "title": "Mr"]]

Hope it helped.

like image 27
Ahmad F Avatar answered May 12 '26 07:05

Ahmad F