2016-10-17 45 views
0

我创建上面的功能检查,如果用户在火力地堡数据库存在后不保留:雨燕2.2超值功能执行

func userExists(userUid: String) -> Bool { 
    var userExists: Bool = false 
    DBRef.child("users").child(userUid).observeSingleEventOfType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in 
     if snapshot.exists(){ 
      userExists = true 
     }else{ 
      userExists = false 
     } 
    }) 
    return userExists 
} 

的问题是,userExists函数总是返回“假”,即使在withBlock中将userExists变量设置为true。请帮忙吗?谢谢!

回答

1

您不应该在同一个函数中使用return和closure块,因为函数将在块执行之前返回值。 您可以使用这样的事情:

func userExists(userUid: String, completion: (exists: Bool) -> Void) { 
    var userExists: Bool = false 
    DBRef.child("users").child(userUid).observeSingleEventOfType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in 
     if snapshot.exists(){ 
      completion(true) 
     }else{ 
      completion(false) 
     } 
    }) 
} 

然后,您只要致电:

if userExists(userId, completion: { 
    // Code here 
}) 
+0

它的工作,aramusss。谢谢。我只是修改了通话功能 – Enzo

+0

它的工作,aramusss。谢谢。我只是用这种方式修改了调用函数: – Enzo