引用数组里面斯威夫特功能 [英] Reference to array inside function in Swift
问题描述
我想引用一个函数里的数组。结果
事情是这样的: A
和 B
是内部
阵列秒。
I am trying to reference to an array inside a function.
Something like this: a
and b
are arrays of Int
s.
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.
因此,为了使这项工作安全,你必须添加一些code:
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
}
}
}
这是一个有点难看。
which is a bit ugly.
这篇关于引用数组里面斯威夫特功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!