Swift 为什么不是';t此[Int]-类型为';Int';?
我试图编写一个简单的冒泡排序函数:Swift 为什么不是';t此[Int]-类型为';Int';?,swift,Swift,我试图编写一个简单的冒泡排序函数: func bubbleSort(array: [Int]) -> [Int] { while !isSorted(array) { for index in 1..<array.count { if array[index - 1] > array[index] { let temp: Int = array[index]
func bubbleSort(array: [Int]) -> [Int] {
while !isSorted(array) {
for index in 1..<array.count {
if array[index - 1] > array[index] {
let temp: Int = array[index]
array[index] = array[index - 1]
array[index - 1] = temp
}
}
}
return array
}
let res = bubbleSort(&myArray)
func bubbleSort(数组:[Int])->[Int]{
while!isSorted(数组){
对于1中的索引..编译代码,但它给了我以下错误消息:
<stdin>:17:17: error: '@lvalue $T11' is not identical to 'Int'
array[index] = array[index - 1]
^
<stdin>:18:17: error: '@lvalue $T8' is not identical to 'Int'
array[index - 1] = temp
^
:17:17:错误:“@lvalue$T11”与“Int”不同
数组[索引]=数组[索引-1]
^
:18:17:错误:“@lvalue$T8”与“Int”不相同
数组[索引-1]=临时
^
(如果您想在网站上查看:)
array[index]
和array[index-1]
怎么可能不是类型Int
,它们怎么可能是不同的类型呢?这是因为传递给函数的数组是不可变的。为了使其可变,必须使用inout
修饰符通过引用传递它:
func bubbleSort(inout array: [Int]) -> [Int] {
请注意,使用inout
时,在调用函数时,必须使用&
运算符传递相应的参数作为引用:
func bubbleSort(array: [Int]) -> [Int] {
while !isSorted(array) {
for index in 1..<array.count {
if array[index - 1] > array[index] {
let temp: Int = array[index]
array[index] = array[index - 1]
array[index - 1] = temp
}
}
}
return array
}
let res = bubbleSort(&myArray)
还请注意,要交换2个变量,您只需使用:
swap(&array[index], &array[index - 1])
建议阅读:那不是通过引用传递数组吗,这意味着它会改变数组的原始版本吗?你必须使用&
操作符-阅读更新的答案,但也要阅读链接的文档好的,没错…让我们假设我不想通过引用传递数组,所以原始版本不是c挂起。我该怎么做?@445646:func bubbleSort(var数组:[Int])->[Int]
谢谢@MartinR。var
使参数可变,但这当然只是一个副本。因此传递给函数的原始数组不受func体内部所做任何更改的影响。