Swift Language Arrays Sorting an Array

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

var array = [3, 2, 1]

Creating a new sorted array

As Array conforms to SequenceType, we can generate a new array of the sorted elements using a built in sort method.

2.12.2

In Swift 2, this is done with the sort() method.

let sorted = array.sort()  // [1, 2, 3]
3.0

As of Swift 3, it has been re-named to sorted().

let sorted = array.sorted()  // [1, 2, 3]

Sorting an existing array in place

As Array conforms to MutableCollectionType, we can sort its elements in place.

2.12.2

In Swift 2, this is done using the sortInPlace() method.

array.sortInPlace() // [1, 2, 3]
3.0

As of Swift 3, it has been renamed to sort().

array.sort() // [1, 2, 3]

Note: In order to use the above methods, the elements must conform to the Comparable protocol.

Sorting an array with a custom ordering

You may also sort an array using a closure to define whether one element should be ordered before another – which isn't restricted to arrays where the elements must be Comparable. For example, it doesn't make sense for a Landmark to be Comparable – but you can still sort an array of landmarks by height or name.

struct Landmark {
    let name : String
    let metersTall : Int
}

var landmarks = [Landmark(name: "Empire State Building", metersTall: 443),
                 Landmark(name: "Eifell Tower", metersTall: 300),
                 Landmark(name: "The Shard", metersTall: 310)]
2.12.2
// sort landmarks by height (ascending)
landmarks.sortInPlace {$0.metersTall < $1.metersTall}

print(landmarks) // [Landmark(name: "Eifell Tower", metersTall: 300), Landmark(name: "The Shard", metersTall: 310), Landmark(name: "Empire State Building", metersTall: 443)]

// create new array of landmarks sorted by name
let alphabeticalLandmarks = landmarks.sort {$0.name < $1.name}

print(alphabeticalLandmarks) // [Landmark(name: "Eifell Tower", metersTall: 300), Landmark(name: "Empire State Building", metersTall: 443), Landmark(name: "The Shard", metersTall: 310)]
3.0
// sort landmarks by height (ascending)
landmarks.sort {$0.metersTall < $1.metersTall}

// create new array of landmarks sorted by name
let alphabeticalLandmarks = landmarks.sorted {$0.name < $1.name}

Note: String comparison can yield unexpected results if the strings are inconsistent, see Sorting an Array of Strings.



Got any Swift Language Question?