如何将闭包的值设置为函数结果
How to set value of closure as function result
我卡住了。我试图找到解决我的问题的好方法,但我不能...所以我想问你,我怎样才能获取闭包的价值并将其作为 func 结果?我想从不同 id child 的 firebase 中获取数据。所以我的 func 正在工作 - "print(target!)" 打印好东西,但我怎样才能把它作为 func 结果字符串?
func readID(id: Int) -> String {
var value = ""
let ref1 = ref.child("\(av.currentYear())/\(av.currentMonth())/\(av.currentDay())/Shift\(av.shift)/\(id)").child("main").child("id")
ref1.observeSingleEvent(of: .value) { (snapshot1) in
if snapshot1.exists(){
let target = snapshot1.value as? String
print(target!)
value = target!
}
}
return value
}
我对 var 值的想法行不通,我不想在函数外创建 10 个不同的变量。我想尝试使用转义闭包,但我还不明白...
func readID(id: Int, completion: @escaping ((String)->())) {
var value = ""
let ref1 = ref.child("\(av.currentYear())/\(av.currentMonth())/\(av.currentDay())/Shift\(av.shift)/\(id)").child("main").child("id")
ref1.observeSingleEvent(of: .value) { (snapshot1) in
if snapshot1.exists(){
let target = snapshot1.value as? String
print(target!)
value = target!
}
completion(value)
}
}
您可以获得 return 值:
readId(30, completion: {
[weak self] value in
self?.text = "This is my \(value)"
})
我卡住了。我试图找到解决我的问题的好方法,但我不能...所以我想问你,我怎样才能获取闭包的价值并将其作为 func 结果?我想从不同 id child 的 firebase 中获取数据。所以我的 func 正在工作 - "print(target!)" 打印好东西,但我怎样才能把它作为 func 结果字符串?
func readID(id: Int) -> String {
var value = ""
let ref1 = ref.child("\(av.currentYear())/\(av.currentMonth())/\(av.currentDay())/Shift\(av.shift)/\(id)").child("main").child("id")
ref1.observeSingleEvent(of: .value) { (snapshot1) in
if snapshot1.exists(){
let target = snapshot1.value as? String
print(target!)
value = target!
}
}
return value
}
我对 var 值的想法行不通,我不想在函数外创建 10 个不同的变量。我想尝试使用转义闭包,但我还不明白...
func readID(id: Int, completion: @escaping ((String)->())) {
var value = ""
let ref1 = ref.child("\(av.currentYear())/\(av.currentMonth())/\(av.currentDay())/Shift\(av.shift)/\(id)").child("main").child("id")
ref1.observeSingleEvent(of: .value) { (snapshot1) in
if snapshot1.exists(){
let target = snapshot1.value as? String
print(target!)
value = target!
}
completion(value)
}
}
您可以获得 return 值:
readId(30, completion: {
[weak self] value in
self?.text = "This is my \(value)"
})