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

The Complete iOS 11 & Swift Developer Course - Build 20 Apps

Use Xcode 9 & Swift 4 to make real apps like Uber and Instagram, with CoreML & ARKit. Includes AWS Credit and much more. Preview this video course. icon

How to Make a Freaking iPhone App - iOS 11 and Swift 4

iPhone App Development from scratch. Learn how to make iOS apps using Xcode 9. The Basics Include Pokemon Go & Snapchat. Learn to build iOS Apps with Xcode 9 and Swift 4. How to Make a Freaking iPhone App - iOS 11 and Swift 4 icon

iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course

A Complete iOS 11 and Xcode 9 Course with Swift 4 & Objective-C. Preview this video course. iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course icon