【问题标题】:Swift: inout with generic functions and constraintsSwift:具有通用函数和约束的 inout
【发布时间】:2023-04-07 14:07:01
【问题描述】:

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

我在 Xcode 中调用exchange 时遇到以下错误:

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

我在这里错过了什么吗?

更新:添加了完整的项目代码。

【问题讨论】:

  • 也许发布给出错误的实际代码....
  • 我添加了完整的项目代码。交换函数实际上并没有对数组做任何事情,所以这是最小的例子。

标签: swift generics inout


【解决方案1】:

它适用于以下修改:

  • 传入的数组必须是 var。 As mentioned in the documentation,inouts 不能是 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)

【讨论】:

    【解决方案2】:

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

    例如

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

    表示a 现在是 [2, 1, 3, 4, 5]

    【讨论】:

    • 是的,我知道。但这不是我要求的问题。
    猜你喜欢
    • 1970-01-01
    • 2018-07-28
    • 2021-01-30
    • 1970-01-01
    • 2017-11-23
    • 2021-03-08
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多