在 Swift 中使用闭包从函数中检索字符串值 [英] Retrieve String value from function with closure in Swift
问题描述
我正在尝试从 Firebase 检索字符串值,以便获取每个用户名和传递给该函数的唯一 UID,该函数返回用户的用户名.但是 - 由于 firebase ObserveEvent
在 closures
中,我无法返回任何值,因为操作发生异步(?).我想知道这是否是一种实现方式?
I am trying to retrieve a string value from Firebase in order to get each username with an unique UID that is passed to the function, which returns the username of the user. However - since the firebase ObserveEvent
is in closures
, I can't return any value back because the actions happens asynchronous(?). I was wondering if it was a way of accomplishing this?
函数如下所示:
func GetUsername(uid:String) -> String {
var username = String()
firebase.child("Users").child(uid).observeSingleEventOfType(.Value) { (snapshot:FIRDataSnapshot) in
username = snapshot.value!["Username"] as! String
}
return username
}
显然这不起作用,但我希望能够通过执行 GetUsername("whatevertheidmightbe") 来获取数据.想法?
Obviously this doesn't work, but I want to be able to get the data by doing a GetUsername("whatevertheidmightbe"). Ideas?
推荐答案
你需要像这样创建完成处理程序
You need to create completion handler like this
func GetUsername(uid:String , completion: (String) -> ()) {
firebase.child("Users").child(uid).observeSingleEventOfType(.Value) { (snapshot:FIRDataSnapshot) in
if let username = snapshot.value!["Username"] as? String
completion(username)
}
else {
completion("")
}
}
然后这样调用函数
self.GetUsername(str) { (name) -> () in
if name.characters.count > 0 {
print(name)
}
else {
print("Not found")
}
}
这篇关于在 Swift 中使用闭包从函数中检索字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!