create a function that implements bubble sort in swift

Here's an implementation of bubble sort in Swift:

main.swift
func bubbleSort(_ array: inout [Int]) {
    guard array.count > 1 else { return }

    for i in 0..<array.count {
        var swapped = false
        for j in 1..<array.count-i {
            if array[j] < array[j-1] {
                array.swapAt(j, j-1)
                swapped = true
            }
        }
        if !swapped { return }
    }
}
349 chars
15 lines

To use this function, you would simply call it like so:

main.swift
var array = [42, 23, 12, 17, 8, 91]
bubbleSort(&array)
print(array) // [8, 12, 17, 23, 42, 91]
95 chars
4 lines

Note that the array parameter is marked as inout, which means that the function can modify the array in place. This is necessary for bubble sort since it involves swapping elements in the array.

gistlibby LogSnag