Skip to content

Latest commit

 

History

History
41 lines (32 loc) · 871 Bytes

sort-an-array.md

File metadata and controls

41 lines (32 loc) · 871 Bytes

Sort An Array

Category: Swift

Given a struct in Swift:

struct Manufacturer {
    var name: String
    var website: String
}

Assuming you have created the following array:

var manufacturers = [
    Manufacturer(name: "BMW", website: "https://www.bmw.com"),
    Manufacturer(name: "Toyota", website: "https://www.toyota.com"),
    Manufacturer(name: "Honda", website: "https://www.honda.com.au"),
    Manufacturer(name: "Audi", website: "https://www.audi.de"),
    Manufacturer(name: "Porsche", website: "https://www.porsche.com"),
    Manufacturer(name: "Nissan", website: "https://www.nissan.co.jp")
]

Sort the array in place as follows:

manufacturers.sort {
    $0.name < $1.name
}

Or create a sorted array from an existing array:

let sortedManufacturers = manufacturers.sorted {
    $0.name < $1.name
}