I'm creating a simple selection sort in Swift. In my sort method I'm getting an error when calling method for exchanging values within the array.
class func sort(a:[String]) {
var N = a.count
for(var i = 0; i < N; i++) {
var min = i
for(var j = i+1; j < N; j++) {
if(less(a[i], str2:a[j])) {
min = j
}
}
exch(&a, i, min) // Error: [String] not convertible to @value inout $T3
}
}
Exch method:
class func exch(inout a:[String], i:Int, j:Int) {
let temp = a[i]
a[i] = a[j]
a[j] = temp
}
Thanks for the help! :)
arguments are immutable by default, whereas inout
parameters are mutable, so the problem is that you can't convert immutable a
to mutable inout
parameter. you need to declare it with var
to make it mutable
class func sort(var a:[String]) { // declare a with var. by default it is using let
var N = a.count
for(var i = 0; i < N; i++) {
var min = i
for(var j = i+1; j < N; j++) {
if(less(a[i], str2:a[j])) {
min = j
}
}
exch(&a, i, min) // Error: [String] not convertible to @value inout $T3
}