如何从Swift的另一个函数中返回期望值?

时间:2019-03-04 17:31:36

标签: swift firebase

我有一个函数返回一个布尔值,以检查用户是否已对帖子进行投票。但是,我正在努力获取正确的布尔值来返回。我运行Firebase查询以检查后端中的数据,但始终返回默认值false的布尔值。解决此逻辑的最佳方法是什么?

我了解为什么默认将其设置为false:我将其设置在块上方,然后代码在查询完成之前命中return false。最好的方法是什么?

func didAlreadyVote(message: MessageType) -> Bool {

    // check user votes collection to see if current message matches
    guard let currentUser = Auth.auth().currentUser else {return false}
    let userID = currentUser.uid
    var bool = false
    let docRef = Firestore.firestore().collection("users").document(userID).collection("upvotes").whereField("messageId", isEqualTo: message.messageId)

    docRef.getDocuments { querySnapshot, error in

        if let error = error {
            print("Error getting documents: \(error)")
            bool = false
        } else {
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")
                bool = true
            }
        }
    }
    return bool
}

1 个答案:

答案 0 :(得分:1)

您将在关闭有机会完成之前返回,因此返回值为false。为了解决这个问题,您可以在函数签名中传递另一个闭包:

func didAlreadyVote(message: MessageType, completion: (Bool) -> Void) {

    // check user votes collection to see if current message matches
    guard let currentUser = Auth.auth().currentUser else {return false}
    let userID = currentUser.uid
    let docRef = Firestore.firestore().collection("users").document(userID).collection("upvotes").whereField("messageId", isEqualTo: message.messageId)

    docRef.getDocuments { querySnapshot, error in

        if let error = error {
            print("Error getting documents: \(error)")
            completion(false)
        } else {
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")
                completion(true) /// Note that this will get called multiple times if you have more the one document!
            }
        }
    }
}

用法

didAlreadyVote(message: messageType) { didVote in
        // didVote is the value returned
}