Swift Tutorial

Swift Data Types

Swift Control Flow

Swift Functions

Swift Collections

Swift OOPs

Swift Additional Topics

Sorting an Array in Swift

In Swift, arrays come with a built-in sorted() method that allows you to sort the elements. The method returns a new array containing the sorted elements. If you want to sort the original array in place, you can use the sort() method.

Here's how you can use these methods:

1. Sorting Arrays of Simple Types

For arrays containing elements like numbers or strings, which already conform to the Comparable protocol:

var numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort() // Sorts in-place
print(numbers) // Outputs: [1, 1, 2, 3, 4, 5, 6, 9]

let sortedNumbers = numbers.sorted() // Returns a new sorted array
print(sortedNumbers) // Outputs: [1, 1, 2, 3, 4, 5, 6, 9]

let words = ["apple", "orange", "banana"]
let sortedWords = words.sorted()
print(sortedWords) // Outputs: ["apple", "banana", "orange"]

2. Sorting Using Custom Logic

You can provide a closure to determine the sort order:

let sortedNumbersDescending = numbers.sorted { (a, b) -> Bool in
    return a > b
}
print(sortedNumbersDescending) // Outputs: [9, 6, 5, 4, 3, 2, 1, 1]

A more concise version using shorthand argument names:

let sortedNumbersDescending = numbers.sorted(by: >)
print(sortedNumbersDescending) // Outputs: [9, 6, 5, 4, 3, 2, 1, 1]

3. Sorting Arrays of Custom Types

Suppose you have an array of custom objects:

struct Person {
    var name: String
    var age: Int
}

let people = [Person(name: "John", age: 28), Person(name: "Doe", age: 22), Person(name: "Anna", age: 25)]

You can sort them by a property:

let sortedPeopleByName = people.sorted { $0.name < $1.name }
print(sortedPeopleByName.map { $0.name }) // Outputs: ["Anna", "Doe", "John"]

let sortedPeopleByAge = people.sorted { $0.age < $1.age }
print(sortedPeopleByAge.map { $0.age }) // Outputs: [22, 25, 28]

These are just some basic ways to sort arrays in Swift. Depending on your needs, you might employ more complex sorting logic or use other available methods and tools provided by the language and the standard library.

  1. How to sort an array in Swift:

    • Description: Sorting an array in Swift can be done using the sort() method. By default, it sorts the array's elements in ascending order.

    • Code:

      var numbers = [5, 2, 8, 1, 7]
      numbers.sort()
      print(numbers) // Output: [1, 2, 5, 7, 8]
      
  2. Sorting arrays in Swift using sort method:

    • Description: The sort() method in Swift is used to sort the elements of an array. It can take a closure to define a custom sorting logic.

    • Code:

      var fruits = ["Apple", "Banana", "Orange", "Grapes"]
      fruits.sort()
      print(fruits) // Output: ["Apple", "Banana", "Grapes", "Orange"]
      
  3. Sort array elements in ascending order in Swift:

    • Description: Sorting array elements in ascending order can be achieved using the sort() method without any additional parameters.

    • Code:

      var numbers = [9, 3, 7, 1, 5]
      numbers.sort()
      print(numbers) // Output: [1, 3, 5, 7, 9]
      
  4. Descending order array sorting in Swift:

    • Description: To sort an array in descending order in Swift, you can use the sort(by:) method with a custom sorting closure.

    • Code:

      var numbers = [9, 3, 7, 1, 5]
      numbers.sort { $0 > $1 }
      print(numbers) // Output: [9, 7, 5, 3, 1]
      
  5. Swift sort array of custom objects:

    • Description: You can sort an array of custom objects by conforming to the Comparable protocol or by providing a custom sorting closure.

    • Code:

      struct Person: Comparable {
          var name: String
          var age: Int
      
          static func < (lhs: Person, rhs: Person) -> Bool {
              return lhs.age < rhs.age
          }
      }
      
      var people = [Person(name: "Alice", age: 30), Person(name: "Bob", age: 25), Person(name: "Charlie", age: 35)]
      people.sort()
      print(people)
      
  6. Sorting integers in an array with Swift:

    • Description: Sorting an array of integers in Swift is straightforward using the sort() method.

    • Code:

      var numbers = [8, 3, 6, 1, 9]
      numbers.sort()
      print(numbers) // Output: [1, 3, 6, 8, 9]
      
  7. Using closures for custom sorting in Swift:

    • Description: Custom sorting in Swift can be achieved by providing a closure to the sort(by:) method.

    • Code:

      var words = ["Apple", "Banana", "Orange", "Grapes"]
      words.sort { $0.count < $1.count }
      print(words) // Output: ["Apple", "Banana", "Orange", "Grapes"]
      
  8. Sort array of strings alphabetically in Swift:

    • Description: Sorting an array of strings alphabetically is the default behavior when using the sort() method.

    • Code:

      var names = ["Alice", "Charlie", "Bob"]
      names.sort()
      print(names) // Output: ["Alice", "Bob", "Charlie"]