Sorting an Array

suggest change
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.

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

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

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.

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

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

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)]
// 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)]
// 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents