2016-06-20 95 views
1

我创建了一个函数,在userID参数上返回带有Firebase查询的用户名。我想用这个用户名填充tableView中的文本标签。虽然函数内的查询返回正确的值,但该值似乎不会返回:swift函数不返回字符串?

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 
    } 
} 

单元格没有文本。打印函数返回到控制台只是打印空白。任何想法,以什么是错的?

谢谢!

回答

1

你的问题是,你getUser函数执行的块,以获得full_name值,但你要返回另一个线程,所以,当这行return full_name执行,几乎是不可能的,你的块的结束,以便您的函数返回""代替你所需的值

试试这个,而不是

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我不知道,如果这个工程,因为我没有这个库

+0

工作!所以...你的解决方案为什么工作?什么是“封闭”?非常感谢!! – winston