本文介绍了如何在迅速函数返回一个INOUT(参考)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个函数返回一个数组的引用:

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

我无法返回&放大器;一个和b arrayToPick 因为那些不能被强制转换为 [INT]

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

如何返回一个引用 A B 从函数?

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

推荐答案

您不能返回 INOUT 值。因为编译器不能保证值的寿命。

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

在这种情况下,后 A 被释放, d.memory 访问可能会引起 BAD_ACCESS 错误。

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

安全的方式,像这样的:

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.

这篇关于如何在迅速函数返回一个INOUT(参考)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 19:46