2016-06-20 174 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