Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bubble sorting an array in Swift, compiler error on swap

I wrote a really simple bubble sort for a card game. It takes an array of "Card" objects, each of which has a an "order" attribute which indicates the value to be sorted against for the game in question.

The following code stopped compiling some time between Swift Beta 1 and Beta 6, and I'm not exactly sure why.

 ///Sort the cards array by order
  func sortCards(cards: Array<Card>) -> Array<Card> {
    var sorted = false
    while sorted == false {
      sorted = true
      for i in 0...cards.count - 2 {
        if cards[i].order > cards[i+1].order {
          sorted = false
          var first = cards[i]
          var second = cards[i + 1]
          cards[i] = second    //ERROR
          cards[i + 1] = first //ERROR
        }
      }
    }
    return cards
  }

The lines where the swap occurs bombs out with a very cryptic message:

@!value $T5 is not identical to 'Card'

What changed, and what am I doing wrong here?

Bonus question: How am I supposed to understand the error message?

like image 762
Mikey T.K. Avatar asked May 17 '26 06:05

Mikey T.K.


1 Answers

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

bubble sort:

func bubble(arr: inout [Int]) {
    for i in (1..<arr.count).reversed() {
        for j in 0..<i where arr[j] > arr[j + 1] {
            swap(&arr[j], &arr[j + 1])
        }
    }
}

using stride:

func bubbleStride(arr: inout [Int]) {
    for i in stride(from: arr.count - 1, to: 1, by: -1) {
        for j in 0..<i where arr[j] > arr[j + 1] {
            swap(&arr[j], &arr[j + 1])
        }
    }
}

using while:

func bubbleWhile(arr: inout [Int]) {
    var i = arr.count - 1
    while(i > 0) {
        var j = 0
        while(j < i) {
            if arr[j] > arr[j + 1] {
                swap(&arr[j], &arr[j + 1])
            }
            j += 1
        }
        i -= 1
    }
}

This can be used to generate a random array of integers:

import Cocoa

func ints(cnt: Int, ceiling: Int) -> [Int] {
    let arr = Array(repeating: 0, count: cnt)
    return arr.map { _ in Int(arc4random_uniform(UInt32(ceiling))) }
}

E.g.:

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

var b = a
bubble(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]
like image 84
Golden Thumb Avatar answered May 18 '26 19:05

Golden Thumb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!