我正在尝试在Swift中实现常见的算法。
即使我没有将数字定义为let变量,但我也遇到以下错误:
无法通过下标分配:“数字”是一个“ let”常量 数字[i] = maxNumber
我的实现如下:
func InsertionSort (numbers : [Int]) -> [Int]
{
var maxNumber = 0
var j = 0
var size = numbers.count-1
for (i,number) in numbers.enumerated()
{
j = i + 1
for index in j...size
{
if numbers[index] > number
{
maxNumber = numbers[index]
numbers[index] = numbers[i]
// error is thrown in the following line
numbers[i] = maxNumber
}
}
}
return numbers
}
答案 0 :(得分:2)
默认情况下参数是不可变的。要使参数可变,您需要添加一个inout
修饰符。
但是,看到您的方法返回一个数组,您可能不希望同时修改参数。相反,您应该复制该参数,对其进行修改,然后返回该副本:
func InsertionSort (numbers : [Int]) -> [Int]
{
var maxNumber = 0
var j = 0
let size = numbers.count-1
var numbersCopy = numbers // <------ note this line
for (i,number) in numbers.enumerated()
{
j = i + 1
for index in j...size
{
if numbers[index] > number
{
maxNumber = numbers[index]
// note how I modified the copy here
numbersCopy[index] = numbers[i]
numbersCopy[i] = maxNumber
}
}
}
return numbersCopy
}