我需要从该函数返回一个值,并且我有2个参数。我无法完成转义功能。 如何使其逃脱?
func myReturn(str:String,userCU:String)->String{
var res = ""
let refU = Database.database().reference(withPath: "users")
refU.child(userCU).observeSingleEvent(of:.value) {
(snapshot) in
if snapshot.exists(){
// print(snapshot)
let dict = snapshot.value as! [String:Any]
print(dict)
//dict["userCity"]
res = dict[str] as! String
print(res)
}
else {
print("noooooo")
}
}
print(res)
return res
}
答案 0 :(得分:1)
作为起点,我考虑在数据库调用失败的情况下返回可选的String
。
func getStringAsync(str: String, usr: String, completion: @escaping (String?) -> Void) {
Database.database().reference(withPath: "users").child(usr).observeSingleEvent(of: .value) { (snapshot) in
if let snapshot = snapshot,
let d = snapshot.value as? [String: Any],
let result = d[str] as? String {
completion(result)
} else {
completion(nil)
}
}
}
然后处理可选的String
:
getStringAsync(str: "abc", usr: "xyz") { (str) in
if let str = str {
print(str)
}
}