简体   繁体   中英

Swift: inout with generic functions and constraints

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.

It works with following modifications:

  • the array passed into it must be a var. As mentioned in the documentation , inouts must not be let or literals.

    You cannot pass a constant or a literal value as the argument, because constants and literals cannot be modified.

  • items in declaration must also be inout to indicate that it must be var again


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)

You can "exchange" two values in an array by using the swift swap function.

eg

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

would mean that a now is [2, 1, 3, 4, 5]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM