sort an array in swift

To sort an array in Swift, you can use the sort() method. Here's an example:

main.swift
var myArray = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
myArray.sort()

print(myArray) // Output: [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
118 chars
5 lines

This will sort the array in ascending order. To sort in descending order, you can use the sort(by:) method with a custom closure:

main.swift
var myArray = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
myArray.sort(by: { $0 > $1 })

print(myArray) // Output: [9, 6, 5, 5, 4, 3, 3, 2, 1, 1]
133 chars
5 lines

This will sort the array in descending order.

related categories

gistlibby LogSnag