Laurent Meyer Laurent Meyer - 1 month ago 9
Swift Question

Swift modify Int array for InsertionSort algorithm

I'm very new to Swift and I wanted to know how I'm supposed to modify an

Int
contained in my
Int[]
? I made it like I'd do it in Java but it, obviously, doesn't work: I get a
Cannot assign to immutable value of type 'Int'
compilation error.

Here is my code:

import Foundation

func createRandomArray(length: Int) -> [Int]{
var random = [Int]()
for index in 0...length{
random.append(Int(arc4random_uniform(100)))
}
return random
}

func insertionSort(toSort: [Int]) -> [Int]{
var length = toSort.count
for index in 1...length-1{
var key = toSort[index]
var previous = index-1
while(previous>0 && toSort[previous]>key){
// ERROR IS THERE
toSort[previous+1] = toSort[previous]
previous--
}
}
return toSort
}

var array = createRandomArray(10)

print(array)

print(insertionSort(array))


I thought that using a
var
instead of
let
will give a mutable object so that's why I'm a bit lost.

Thanks for help

EDIT:

I got this working answer yet, thanks to @vacawama:

import Foundation

func createRandomArray(length: Int) -> [Int]{
var random = [Int]()
for index in 0...length{
random.append(Int(arc4random_uniform(100)))
}
return random
}

func insertionSort(var toSort: [Int]) -> [Int]{
for firstIterator in 1...toSort.count-1{
var currentValue = toSort[firstIterator]
var previousPosition = firstIterator-1
while(previousPosition>=0 && toSort[previousPosition]>currentValue){
swap(&toSort[previousPosition+1], &toSort[previousPosition])
previousPosition--
}
}
return toSort
}


var array = createRandomArray(10)

print(array)

print(insertionSort(array))

Answer

By default, array parameters are immutable within the called function. If you want to modify the copy of the array that is passed to insertionSort, add var before toSort in the function header.

func insertionSort(var toSort: [Int]) -> [Int]{
Comments