我正在 Swift 中迈出第一步,并解决了第一个问题。我正在尝试在具有约束的通用函数上使用 inout
通过引用传递数组。
首先,我的申请起点:
import Foundation
let sort = Sort()
sort.sort(["A", "B", "C", "D"])
这里是我的类(class)的实际问题:
import Foundation
class Sort {
func sort<T:Comparable>(items:[T]){
let startIndex = 0
let minIndex = 1
exchange(&items, firstIndex: startIndex, secondIndex: minIndex)
}
func exchange<T:Comparable>(inout array:[T], firstIndex:Int, secondIndex:Int) {
// do something with the array
}
}
我在调用 exchange
的 Xcode 中收到以下错误:
Cannot convert value of type '[T]' to expected argument type '[_]'
我是不是漏掉了什么?
更新:添加了完整的项目代码。
最佳答案
它适用于以下修改:
传递给它的数组必须是一个 var。 As mentioned in the documentation , inouts 不能是 let 或文字。
You cannot pass a constant or a literal value as the argument, because constants and literals cannot be modified.
声明中的项也必须是inout,表示它又必须是var
import Foundation
class Sort {
func sort<T:Comparable>(inout items:[T]){
let startIndex = 0
let minIndex = 1
exchange(&items, firstIndex: startIndex, secondIndex: minIndex)
}
func exchange<T:Comparable>(inout array:[T], firstIndex:Int, secondIndex:Int) {
// do something with the array
}
}
let sort = Sort()
var array = ["A", "B", "C", "D"]
sort.sort(&array)
关于Swift:具有通用函数和约束的 inout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35974861/