11. 3. Sorting an array of custom data
Let's look at the following example:
import UIKit
struct User{
var name: String
var age: Int
var city: String
}
var users = [
User(name: "Alice", age: 12, city: "Boston"),
User(name: "Bob", age: 21, city: "Charlotte"),
User(name: "Chris", age: 45, city: "NYC"),
User(name: "David", age: 23, city: "Boston"),
User(name: "Dillon", age: 89, city: "San Francisco"),
]
//MARK: sort by name in decreasing order
users.sort(by: { (user1:User, user2:User)-> Bool in
return user1.name > user2.name
})
for user in users{
print(user)
}
/*prints:
User(name: "Dillon", age: 89, city: "San Francisco")
User(name: "David", age: 23, city: "Boston")
User(name: "Chris", age: 45, city: "NYC")
User(name: "Bob", age: 21, city: "Charlotte")
User(name: "Alice", age: 12, city: "Boston")
*/
//MARK: sort by age in increasing order
users.sort(by: { (user1:User, user2:User)-> Bool in
return user1.age < user2.age
})
for user in users{
print(user)
}
/* prints:
User(name: "Alice", age: 12, city: "Boston")
User(name: "Bob", age: 21, city: "Charlotte")
User(name: "David", age: 23, city: "Boston")
User(name: "Chris", age: 45, city: "NYC")
User(name: "Dillon", age: 89, city: "San Francisco")
*/
This example is pretty self-explanatory. We have a struct to create our custom data type, User. Each user has name, age, and city.
We first want to sort the array of Users based on their name in decreasing order. So, wrote a closure that takes in a pair of User objects. Then compared their names.
The next task is to sort the users in increasing order of their age. The next closure takes care of it.
That's pretty much it about the basics of sorting in Swift.
Last updated
Was this helpful?