Swift 中对函数内部数组的引用 [英] Reference to array inside function in Swift

查看:32
本文介绍了Swift 中对函数内部数组的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试引用函数内的数组.
像这样:abInts 的数组.

I am trying to reference to an array inside a function.
Something like this: a and b are arrays of Ints.

  var inout refArr = &a
  if(!someFlag) {
     refArr = &b
  }
  refArr[someIndex] = 30

这不能编译,我可以只使用 inout 作为函数参数吗?如果是这样,我如何在函数内部创建引用/指针?

This does not compile, can I only use inout for function arguments? If so, how do I do a reference/pointer inside a function?

推荐答案

& 只能用于将变量作为 inout 参数传递给函数.所以最简单的解决方案可能是使用辅助函数在您的函数中:

& can only be used to pass a variable as an inout argument to a function. So the easiest solution is perhaps to use a helper function inside your function:

func foo() {

    func helper(inout array : [Int]) {
        array[2] = 99
    }

    var a = [1, 2, 3, 5, 6]
    var b = [4, 5, 6, 7]
    let someFlag = true

    if someFlag {
        helper(&a)
    } else {
        helper(&b)
    }

    // ...
}

可以使用UnsafeMutableBufferPointer创建对数组的引用:

You can create a reference to the array using UnsafeMutableBufferPointer:

let ref = someFlag ?
    UnsafeMutableBufferPointer(start: &a, count: a.count) :
    UnsafeMutableBufferPointer(start: &b, count: b.count)
ref[2] = 99

但是这个解决方案有两个问题:

But there are two problems with this solution:

  • UnsafeMutableBufferPointer() 创建一个非拥有的引用,所以编译器可能会决定在引用时释放数组仍在使用.
  • 没有对数组进行边界检查.
  • UnsafeMutableBufferPointer() creates a non-owning reference, so the compiler might decide to deallocate the array while the reference is still used.
  • There is no bounds check on the array.

所以为了让这个工作安全,你必须添加一些代码:

So to make this work safely, you have to add some code:

withExtendedLifetime(a) { () -> Void in
    withExtendedLifetime(b) { () -> Void in
        let ref = someFlag ?
            UnsafeMutableBufferPointer(start: &a, count: a.count) :
            UnsafeMutableBufferPointer(start: &b, count: b.count)
        if ref.count > 2 {
            ref[2] = 99
        }
    }
}

有点丑.

这篇关于Swift 中对函数内部数组的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆