在objective-c中,我可以声明一个带有输出参数的函数,我想这就是所谓的按引用传递:
-(void) doTask(int id, output: (NSArray**)results) {
…
results = getResult()
}
然后,我可以访问结果
来检查doTask()
在函数范围之外的输出。
在swift中,它仍然有效吗?
func doTask(id:Int, results:NSArray) -> Void {
…
results = getResult()
}
我可以将 doTask()
的最终结果传递给函数参数 results
并在函数作用域之外访问它吗?
最佳答案
在 Swift 中,您需要将参数标记为 inout
;也就是说,您可以在函数中对其进行写入,并且对变量的更改会在函数范围之外生效:
func doTask(id: Int, inout results: NSArray) -> Void {
// …
results = NSArray()
}
然后要调用该函数,您需要传递该类型的有效变量,并在其后面附加一个&符号:
var results: NSArray()
doTask(4, &results)
关于ios - 将函数结果返回到输出参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32475844/