Swift:具有通用函数和约束的 inout

标签 swift generics inout

我正在 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/

相关文章:

Swift 等同于 Unity3d 协程?

swift - 从类名创建一个 swift2 类

ios - 将 indexpath.row 转移到新的 View Controller ?

.net - 在对象列表中搜索所有属性

swift - 全局函数调用协议(protocol)类型的变异方法。我怎样才能摆脱 var tmp 对象?

python - SWIG 输入类型(C++ 到 Python)

swift - 允许 inout 参数使用默认值

ios - 初始化程序不会覆盖其父类(super class) Swift 2.0 中的指定初始化程序

c# - 如何更正通用排序代码以对可空类型进行排序

c# - 填充具有嵌套列表作为值的字典的正确语法是什么?