【问题标题】:How to return expected value from within another function in Swift? [duplicate]如何从 Swift 的另一个函数中返回期望值? [复制]
【发布时间】:2019-03-04 17:31:36
【问题描述】:

我有一个函数,它返回一个布尔值来检查用户是否已经在帖子上投票。但是,我正在努力让正确的布尔值返回。我运行 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
}

【问题讨论】:

  • 完成块?

标签: swift firebase


【解决方案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
}

【讨论】:

  • 谢谢!我怎样才能调用这个函数?我试过var bool = didAlreadyVote(message: message, completion: (Bool) -> Void),但它返回错误Cannot convert value of type '((Bool) -> Void).Type' to expected argument type '(Bool) -> Void'
  • @winston 我更新了我的答案,希望这会有所帮助!
  • 再次感谢,不幸的是 Xcode 让这变得非常困难!它让我更改为didAlreadyVote(message: MessageType.self as! MessageType),然后代码在该行崩溃:Could not cast value of type 'MessageKit.MessageType.Protocol' (0x10dad4b10) to 'MessageKit.MessageType' (0x10dacd3d8)。啊。我怎样才能告诉 XCode 我想要 message: MessageType 而不是协议?
  • 我可以设置一个变量来等于函数的结果吗?喜欢var bool = didAlreadyVote
  • 该函数需要一个 MessageType 类型的元素,而不是 Type。传入其中一个 MessageType 值。 MessageType.self as! MessageType 这会崩溃。 @温斯顿
猜你喜欢
  • 1970-01-01
  • 2021-12-11
  • 2019-11-05
  • 2016-11-04
  • 1970-01-01
  • 1970-01-01
  • 2020-05-06
  • 2017-03-29
  • 2018-10-07
相关资源
最近更新 更多