gpt4 book ai didi

ios - swift 函数不返回字符串?

转载 作者:行者123 更新时间:2023-11-28 06:41:20 25 4
gpt4 key购买 nike

我创建了一个函数来返回用户名,其中包含对 userID 参数的 Firebase 查询。我想使用此用户名来填充 tableView 中的文本标签。虽然函数内的查询返回了正确的值,但似乎没有返回值:

func getUser(userID: String) -> String {

var full_name: String = ""
rootRef.child("users").child(userID).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
// Get user value
let first_name = snapshot.value!["first_name"] as! String
let last_name = snapshot.value!["last_name"] as! String
full_name = first_name + " " + last_name
print(full_name) // returns correct value
})
return full_name //printing outside here just prints a blank space in console
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

let inviteDict = invites[indexPath.row].value as! [String : AnyObject]
if let userID = inviteDict["invitedBy"] as? String {

let name = getUser(userID)

cell.textLabel!.text = name
}
return cell
}
}

单元格没有文本。打印函数 return to console 只会打印空格。有什么问题吗?

谢谢!

最佳答案

你的问题是你的 getUser 函数执行一个 block 来获取 full_name 值,但是你在另一个线程上返回,所以当这一行 return full_name 执行,几乎不可能你的 block 已经结束所以你的函数返回 "" 而不是你想要的值

试试这个

func getUser(userID: String,closure:((String) -> Void)?) -> Void {

var full_name: String = ""
rootRef.child("users").child(userID).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
// Get user value
let first_name = snapshot.value!["first_name"] as! String
let last_name = snapshot.value!["last_name"] as! String
full_name = first_name + " " + last_name
print(full_name) // returns correct value
closure(full_name)
})
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

let inviteDict = invites[indexPath.row].value as! [String : AnyObject]
if let userID = inviteDict["invitedBy"] as? String {

let name = getUser(userID, closure: { (name) in
cell.textLabel!.text = name
})
}
return cell
}

我希望这对你有帮助,PS 我不确定这是否有效,因为我没有这个库

关于ios - swift 函数不返回字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37932762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com