Bubble sorting an array in Swift, compiler error on swap

前端 未结 6 1230
闹比i
闹比i 2021-01-20 05:22

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

6条回答
  •  北海茫月
    2021-01-20 05:28

    If you declare the function like this, then the array is inmutable. You need to use the keyword inoutlike this:

    func sortCards(inout cards: Array) -> Array {
    //code
    }
    

    Then you call it with &:

    sortCards(&myArray)
    

    Explanation

    The whole model of Arrays and pass by value/reference has changed during the beta process.

    In beta 1 arrays passed into subroutines were only kind of passed by value. Arrays passed by value (and let arrays) were still modifiable as long as you didn't change the length of the array, thus breaking the pass-by-value rules and allowing your original code to work.

    In beta 4 I believe it was, they changed arrays to effectively always be passed by value and changed constant arrays (let) do be truly unmodifiable, which resulted in your code not working and breaking in the compile phase.

    The inout keyword changes the array to be passed by reference instead of by value and changes it from being implicitly defined with let to defined with var, which means the array is now mutable, and changes to the array are seen by the caller.

提交回复
热议问题