18

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 Answer 1

27

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Why can't swift just do reference counting and guarantee the lifetime of the object where it is needed ?
@Droopycom Swift does that, but due to some strange reason, they chose struct to be always by value and class to be always by reference. For an even stranger reason - an array is a struct. Someone should have told them about the operator & and move semantics.
Swift 5 requires a slightly different function call format: withPickedArray(0) { ( picked:inout [Int]) in ......
The "safe" way is not exactly 100% safe. If by any chance you also change "a" or "b" inside the withPickedArray block, you'll get "Simultaneous accesses to 0xXYZ but modification requires exclusive access." runtime error. At least in swift 5.x. Can't see the reason why would one be accessing a/b there, but still, just to be aware.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.