With this Swift code example, I would like to share with you how to sort an array of custom objects in Ascending and Descending order.
- Create a custom Swift class with the name “Friend”,
- Create an Array that can hold custom objects of type Friend,
- Sort Array of custom objects in Ascending and Descending order,
- Iterate through an array of custom objects and print object properties.
Here is a short Swift code example that demonstrates how to implement a custom class in Swift with two properties: name and age.
Create Custom Class in Swift
class Friend { let name : String let age : Int init(name : String, age: Int) { self.name = name self.age = age } }
Sort Array of Custom Objects Code Example in Swift
var friends:[Friend] = [] let friend1 = Friend(name: "Sergey", age: 30) let friend2 = Friend(name: "Bill", age: 35) let friend3 = Friend(name: "Michael", age: 21) friends.append(friend1) friends.append(friend2) friends.append(friend3) printFriends(friends: friends) // Get sorted array in descending order (largest to the smallest number) let sortedFriends = friends.sorted(by: { $0.age > $1.age }) printFriends(friends: sortedFriends) // Get sorted array in ascending order (smallest to the largest number) let sortedFriendsAscendingOrder = friends.sorted(by: { $0.age < $1.age }) printFriends(friends: sortedFriendsAscendingOrder)
Iterate Through Array of Custom Objects in Swift
func printFriends(friends: [Friend]) { for friendEntry in friends { print("Name: \(friendEntry.name), age: \(friendEntry.age)") } }
For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.