var array = [3, 2, 1]

Creating a new sorted array

As [Array](<http://swiftdoc.org/v2.2/type/Array/>) conforms to [SequenceType](<http://swiftdoc.org/v2.2/protocol/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()](<http://swiftdoc.org/v2.2/protocol/SequenceType/#func-generator-element_-comparable-sort>) method.

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

As of Swift 3, it has been re-named to [sorted()](<http://swiftdoc.org/v3.0/protocol/Sequence/#func-iterator-element_-comparable-sorted>).

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

Sorting an existing array in place

As Array conforms to [MutableCollectionType](<http://swiftdoc.org/v2.2/protocol/MutableCollectionType/>), we can sort its elements in place.

In Swift 2, this is done using the [sortInPlace()](<http://swiftdoc.org/v2.2/protocol/MutableCollectionType/#func-index_-randomaccessindextype-sortinplace_>) method.

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

As of Swift 3, it has been renamed to [sort()](<http://swiftdoc.org/v3.0/protocol/MutableCollection/#func-self_-randomaccesscollection-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.