[英]Swift: inout with generic functions and constraints
我正在Swift中迈出第一步,并且遇到了第一个问题。 我正在尝试在具有约束的泛型函数上使用inout
通过引用传递数组。
首先,我的应用程序起点:
import Foundation
let sort = Sort()
sort.sort(["A", "B", "C", "D"])
这是我班上的实际问题:
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。 正如文档中所提到的 ,不能让出局或文字。
您不能传递常量或文字值作为参数,因为不能修改常量和文字。
声明中的项目也必须是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 swap函数在数组中“交换”两个值。
例如
var a = [1, 2, 3, 4, 5]
swap(&a[0], &a[1])
将意味着a
现在是[2,1,3,4,5]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.