How to return an inout (reference) in a swift func

2020-02-28 03:24发布

问题:

I'd like a function to return a reference of an array:

var a = [1, 2]
var b = [3, 4]

func arrayToPick(i:Int) -> [Int] {
    return i == 0 ? a : b
}

inout var d = arrayToPick(0)
d[0] = 6

println(a[0]) // 1
println(d[0]) // 6

I'm unable to return &a or &b in arrayToPick because those can't be casted to [Int].

How to return a reference on a or b from a function?

回答1:

You cannot return inout value. Because the compiler cannot guarantee the lifetime of the value.

You have unsafe way, like this:

var a = [1, 2]
var b = [3, 4]

func arrayToPick(i:Int) -> UnsafeMutablePointer<[Int]> {
    if i == 0 {
        return withUnsafeMutablePointer(&a, { $0 })
    }
    else {
        return withUnsafeMutablePointer(&b, { $0 })
    }
}

var d = arrayToPick(0)
d.memory[0] = 6

println(a[0]) // -> 6

In this case, after a is deallocated, d.memory access may cause BAD_ACCESS error.

Or safe way, like this:

var a = [1, 2]
var b = [3, 4]

func withPickedArray(i:Int, f:(inout [Int]) -> Void) {
    i == 0 ? f(&a) : f(&b)
}

withPickedArray(0) { (inout picked:[Int]) in
    picked[0] = 6
}

println(a[0]) // -> 6

In this case, you can access the picked value only in the closure.