Swift:具有通用函数和约束的 inout
Swift: inout with generic functions and constraints
我正在 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 '[_]'
我是不是漏掉了什么?
更新:添加了完整的项目代码。
您可以使用 swift 交换函数 "exchange" 数组中的两个值。
例如
var a = [1, 2, 3, 4, 5]
swap(&a[0], &a[1])
表示 a
现在是 [2, 1, 3, 4, 5]
它适用于以下修改:
传入的数组必须是var。 As mentioned in the documentation, inouts 不能是 let 或 literals.
You cannot pass a constant or a literal value as the argument, because constants and literals cannot be modified.
declaration中的item也必须是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
通过引用传递数组。
首先,我的申请起点:
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 '[_]'
我是不是漏掉了什么?
更新:添加了完整的项目代码。
您可以使用 swift 交换函数 "exchange" 数组中的两个值。
例如
var a = [1, 2, 3, 4, 5]
swap(&a[0], &a[1])
表示 a
现在是 [2, 1, 3, 4, 5]
它适用于以下修改:
传入的数组必须是var。 As mentioned in the documentation, inouts 不能是 let 或 literals.
You cannot pass a constant or a literal value as the argument, because constants and literals cannot be modified.
declaration中的item也必须是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)