struct Foo {
var i = 0 { didSet { println("Current i: \(i)") } }
func delayedPrint() {
dispatch_async(dispatch_get_main_queue(), { _ in
println("Closure i: \(self.i)")
})
}
mutating func foo() {
delayedPrint()
i++
}
}现在的输出
var a = Foo()
a.foo()是
Current i: 1
Closure i: 0 // I want current value here.我想知道什么是最好的方法,以避免捕获一个象牙副本。
编辑1
是的,搬去上课是我想到的第一件也是唯一一件事,但是.这一次愚弄我以为可以用结构来实现.为什么会起作用?
mutating func foo() {
delayedPrint()
dispatch_async(dispatch_get_main_queue(), { _ in
println("From foo: \(self.i)")
})
delayedPrint()
i++
}输出:
Current i: 1
Closure i: 0
From foo: 1
Closure i: 0发布于 2015-05-05 17:59:49
我认为这里必须使用类而不是结构,因为结构是通过复制传递的,而类是通过引用传递的。
https://stackoverflow.com/questions/30059508
复制相似问题