变量在它自己的初始值中使用,而变量在 init 之后的闭包中使用 [英] Variable used within its own initial value while variable is used inside a closure past init
本文介绍了变量在它自己的初始值中使用,而变量在 init 之后的闭包中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
typealias CBType = () -> Void
class A {
let b = B()
func test() {
let token = b.register { CBType in
self.b.waitFor([token]) // ERROR: Variable used within its own initial value
}
b.dispatch()
}
}
class B {
private var _callbacks = [String:CBType]()
func register(callback: CBType) -> String {
let id = "1234"
_callbacks[id] = callback
return id
}
func dispatch() {
for (_, cb) in self._callbacks {
cb()
}
}
func waitFor(tokens: [String]) {
}
}
A().test()
当我修改测试函数以使用实例变量时,事情又恢复了,但语法感觉有点沉重.
When I modify the test function to use a instance variable, things are working again but that syntax feels a bit heavy.
class A {
let b = B()
var token: String?
func test() {
token = b.register { CBType in
self.b.waitFor([self.token!])
}
b.dispatch()
}
}
为什么我不能在闭包中使用局部变量,因为在最终调用闭包时它会超过初始化时间?
Why can't I use a local variable in the closure since it will be way past initialization when the closure is finally called?
推荐答案
常量 token
在被闭包捕获时没有值.
The constant token
doesn't have a value at the time it is captured by the closure.
您可以改用可变变量,闭包将捕获该变量而不是其值.
You can use a mutable variable instead, and the closure will capture the variable rather the its value.
func test() {
var token = ""
token = b.register {
self.b.waitFor([token])
}
b.dispatch()
}
或者,您可以将令牌作为参数传递给闭包:
Alternatively, you can pass the token as a parameter into the closure:
typealias CBType = (String) -> Void
class A {
let b = B()
func test() {
let token = b.register { theToken in
self.b.waitFor([theToken])
}
b.dispatch()
}
}
class B {
private var _callbacks = [String:CBType]()
func register(callback: CBType) -> String {
let id = "1234"
_callbacks[id] = callback
return id
}
func dispatch() {
for (id, cb) in self._callbacks {
cb(id)
}
}
func waitFor(tokens: [String]) {
println("Wait for \(tokens)")
}
}
A().test()
这篇关于变量在它自己的初始值中使用,而变量在 init 之后的闭包中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文