0

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! :)

oyvindhauge
  • 3,496
  • 2
  • 29
  • 45

2 Answers2

1

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
   }
Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
0

I played with the following using swift 3. Hope it'll help some people who come here.

import Cocoa

func ints(cnt: Int, ceiling: Int) -> [Int] {
    var arr = [Int]()
    for _ in 0 ..< cnt {
        arr.append(Int(arc4random_uniform(UInt32(ceiling))))
    }
    return arr
}

func selection(arr: inout [Int]) {
    for i in 0..<arr.count - 1 {
        var k = i
        for j in i + 1..<arr.count where arr[j] < arr[k] {
            k = j
        }
        if k != i {
            swap(&arr[k], &arr[i])
        }
    }
}

let a = ints(cnt: 10, ceiling: 100)
print(a)

var b = a
selection(arr: &b)
print(b)

output:

[13, 30, 68, 19, 1, 4, 28, 65, 96, 13]
[1, 4, 13, 13, 19, 28, 30, 65, 68, 96]
Golden Thumb
  • 2,531
  • 21
  • 20