Sort Array of Custom Objects in Swift

With this Swift code example I would like to share with you how to sort and Array of custom objects in Ascending and Descending order.

  • Create a custom Swift class with a 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 array of custom objects and print object properties

Here is a short Swift code example which 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)

Here is function that iterates through array of custom objects(Friend) and prints its properties.

Iterate Through Array of Custom Objects in Swift

    func printFriends(friends: [Friend])
    {
        for friendEntry in friends {
            print("Name: \(friendEntry.name), age: \(friendEntry.age)")
        }
    }

Checkout more Swift code examples at Swift Code Examples page.


Learn iOS Development with these Video Courses


How to Make a Freaking iPhone App - iOS 10 and Swift 3
icon icon


iOS 10 & Swift 3: From Beginner to Paid Professional
icon


The Complete iOS 10 Developer Course - Build 21 Apps
icon


Swift 3 - Learn to Code with Apple's New Language
icon icon


Learn How to Build Mobile Apps for iOS with Swift, PHP and MySQL
icon icon

Follow me on one of your favourite social networks to learn about new video tutorials and code examples:

Twitter: @SwiftVideoBlog
Google Plus: https://plus.google.com/+SergeyKargopolov/posts
Facebook: Swift Developer Blog on Facebook