我试图实现并行搜索算法。这个概念是这样的:
作为一个简化示例:我想在0..<n
范围内运行一个随机数生成器,直到它给出0.我希望每次迭代减少n
,这样才能保证成功。到目前为止,这是我的代码:
let queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)
let work : dispatch_function_t = { arg in
let upper = UnsafeMutablePointer<UInt32>(arg).memory
let random = arc4random_uniform(upper)
if random == 0 {
// do things
} else {
dispatch_async_f(queue, &(upper - 1), work)
// Error: Variable used within its own initial value
}
}
dispatch_async_f(queue, &1000, work)
// Error: '&' used for non inout argument of type 'UnsafeMutablePointer<Void>'
我有两个错误:
Variable used within its own initial value
'&' used for noninout argument of type 'UnsafeMutablePointer<Void>'
我该如何解决?非常感谢提前!
答案 0 :(得分:0)
您可以通过两个步骤进行声明和初始化来修复“在其自己的初始值中使用”。
let work: dispatch_function_t
work = { arg in
let upper = UnsafeMutablePointer<UInt32>(arg).memory
let random = arc4random_uniform(upper)
if random == 0 {
// do things
} else {
dispatch_async_f(queue, &(upper - 1), work)
// Error: Variable used within its own initial value
}
}
你可以像这样修复另一个。
var n = 1000
dispatch_async_f(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), &n, work)