我希望能够在 block 外部使用 currentVote Int,其中 currentVote 是定义在类顶部的变量。
databaseRef.child("Jokes").child(currentKey).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
if let currentNumber = snapshot.value! as? [String: AnyObject] {
let currentValue = (currentNumber["votes"] as? Int)!
self.currentVote = currentValue
}
})
//*Location* where i want to use currentVote with it's new value
Location 就是我要使用 currentVote 值的地方。当我在这里打印值时,我返回 nil,此后我将返回预期值。当我打印 block 内的值时,我得到了预期值。我明白为什么会这样,因为 block 是在主线程之外执行的,因此当我在 block 外打印时,打印是在 block 之前执行的,因此它的值为 nil。我知道要将它放到主线程上,你必须使用
dispatch_async(dispatch_get_main_queue(), {
code
})
但是,我已经通过此调度调用以多种不同方式嵌套了我的代码,但无法获得 currentVote 的新值。我搜索了堆栈溢出,用户建议在 block 外部创建一个函数,然后在内部调用它。然而,它们的功能涉及
func printValue(value: Int) {
print(value)
}
如您所见,这对我来说毫无用处,因为我想使用 block 外的值,而不是打印它!
***根据 Cod3rite 建议更改代码****
func get(completion: (value: Int) -> Void) {
databaseRef.child("Jokes").child(currentKey).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
if let currentNumber = snapshot.value! as? [String: AnyObject] {
let currentValue = (currentNumber["votes"] as? Int)!
self.currentVote = currentValue
completion(value: self.currentVote!)
}
})
}
//where I want to use currentVote
我已经按提示补全了,但是还是不知道怎么获取变量!
最佳答案
你几乎做对了。但这里有一些您需要做的小修改:
func get(completion: (value: Int) -> Void) {
databaseRef.child("Jokes").child(currentKey).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
if let currentNumber = snapshot.value! as? [String: AnyObject] {
let currentValue = (currentNumber["votes"] as? Int)!
completion(value: currentValue)
}
})
}
现在当你想调用这个get
时,这样做:
get { value in
//Now you have your value retrieved from firebase and you can use it however you want.
print(value)
self.currentVote = value
//your other code
}
关于swift - 从 Block Swift 中提取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38422488/