1

I'm trying to work out an example which is provided on developer.apple.com website 'Swift Playground'. I had to adapt it a little since swift 2 is, what looks like, different in handling 'inout' variables. In the example showed on the presentation 'inout' was not used in the function declaration. Anyway the result of 'data' is not showing in the Playground although the code doesn't show any compile errors.

import UIKit

var data = [16, 97, 13, 55, 95, 53, 18, 10, 79, 53, 79, 34, 50, 34, 0, 91, 94, 55, 6, 38, 7]

func exchange<T>(inout data:[T], i: Int, j: Int) {
    let temp = data[i]
    data[i] = data[j]
    data[j] = temp
}

func swapLeft<T: Comparable>(inout data: [T], index: Int) {
    for i in reverse(1...index) {
        if data[i] < data[i-1] {
            exchange(&data, i, i-1)
        }else {
            break
        }
    }
}

func isort<T: Comparable>(inout data: [T]) {
    for i in 1...data.count {
        swapLeft(&data,i)
    }
}
data //result [16, 97, 13, 55, 95, 53, 18, 10, 79, 53, 79, 34, 50, 34, 0, 91, 94, 55, 6, 38, 7]
isort(&data)
data //no result shown

Screenshot Screenshot Playground

Floern
  • 33,559
  • 24
  • 104
  • 119
Olivier de Jonge
  • 1,454
  • 2
  • 15
  • 31
  • 2
    I think you got the correct answer now, but as an additional hint: You could have found the error yourself in the "Assistant Editor" (View -> Assistant Editor -> Show Assistant Editor). Also, if anything goes wrong in the Playground, I can only recommend to test the code in a compiled project (better error messages, better debugging possibilities). – Martin R Aug 13 '15 at 10:56

2 Answers2

2

It isn't showing a result because it is crashing with Array index out of range. Try this for isort:

func isort<T: Comparable>(inout data: [T]) {
    for i in 1..<data.count {
        swapLeft(&data,i)
    }
}
vacawama
  • 150,663
  • 30
  • 266
  • 294
1

You can always use println(data)

Make sure your Debug Area is shown. See this post for more info.

Community
  • 1
  • 1
Roland Keesom
  • 8,180
  • 5
  • 45
  • 52