错误:不能对不可变值使用变异成员:‘array’是‘let’常量

ryevplcw  于 2022-10-23  发布在  Swift
关注(0)|答案(1)|浏览(112)
import Foundation

func contains(array: [Int], rand: Int) -> Bool{
    for number in array {
        if(number == rand){
            return true
        }
    }
    return false
}

func quicksort(array: [Int], lowIndex: Int, highIndex: Int){
    if(lowIndex >= highIndex){
        return;
    }

    let pivot: Int = array[highIndex]
    var leftPointer = lowIndex
    var rightPointer = highIndex

    while(leftPointer < rightPointer){
        while(array[leftPointer] <= pivot && leftPointer < rightPointer){
            leftPointer = leftPointer + 1
        }

        while(array[rightPointer] >= pivot && leftPointer < rightPointer){
            rightPointer = rightPointer - 1
        }

            array.swapAt(leftPointer, rightPointer)
    }

    if(array[leftPointer] > array[highIndex]){
        array.swapAt(leftPointer, highIndex)
    } else{
        leftPointer = highIndex
    }

    quicksort(array: array, lowIndex: lowIndex, highIndex: leftPointer - 1)
    quicksort(array: array, lowIndex: leftPointer + 1, highIndex: highIndex)
}

func quicksort(array: [Int]){
    quicksort(array: array, lowIndex: 0, highIndex: array.count - 1)
}

func main(){
    var array = [Int.random(in: 0..<30)]
    var jArray = 0

    while(jArray < 20){
        let rand = Int.random(in: 0..<21)
        if(!contains(array: array, rand: rand)){
            array.append(rand)
            jArray = jArray + 1
        }
        else{}
    }

    print("Before:")
    print(array)
    print("\nAfter:")
    quicksort(array: array)
    print(array)    
}

main()

我试图在Swift中实现类似的快速排序,swapAt方法抛出了一个错误:**错误:不能对不变的值使用突变成员:‘array’是一个‘let’常量。**我尝试了几个修复程序,但似乎都不起作用,所以我希望这里有人能帮助我,谢谢。

zte4gxcn

zte4gxcn1#

函数的参数实际上是let常量。有两种方法可以解决这个问题,它们代表了不同的编程范例。第一个是创建参数inout,第二个是返回排序后的数组。
使用inout

func quicksort(array: inout [Int], lowIndex: Int, highIndex: Int)
{
    // sort the array
}

返回排序后的数组

func quicksort(array: [Int]) -> [Int]
{
    var sortingArray = array
    // Do the pivot stuff

    return quicksort(lower bit of sortingArray) + quicksort(upper bit of sortingArray)
}

在后一种情况下,您可以使用泛型和数组切片来做一些有趣的事情,以使它看起来更漂亮,并消除传递索引的需要。

相关问题