簡體   English   中英

Swift:使用泛型函數和約束

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM