1

I am making my first steps in Swift and got along the first problem. I am trying to pass an array by reference using inout on an generic function with constraints.

First, my application start point:

import Foundation

let sort = Sort()
sort.sort(["A", "B", "C", "D"])

And here my class with the actual problem:

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
    }
}

I am getting the following error in Xcode on the line calling exchange:

Cannot convert value of type '[T]' to expected argument type '[_]'

Am I missing here something?

Update: Added complete project code.

4

2 回答 2

3

它适用于以下修改:

  • 传入的数组必须是 var。如文档中所述,输入输出不得为 let 或文字。

    您不能将常量或文字值作为参数传递,因为无法修改常量和文字。

  • 声明中的项目也必须是 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)
于 2016-03-13T20:31:54.853 回答
-3

您可以使用 swift swap 函数“交换”数组中的两个值。

例如

var a = [1, 2, 3, 4, 5]
swap(&a[0], &a[1])

这意味着a现在是 [2, 1, 3, 4, 5]

于 2016-03-13T19:53:36.083 回答