声明Int返回值的函数中void函数中的非预期非无效返回值

时间:2019-02-16 16:26:47

标签: swift

每条返回语句“在void函数中出现非预期的非无效返回值”时,我都会出错。显然这不是void函数,为什么要这么说呢?当我将return语句更改为void时,它表示它正在寻找一个Int。我尝试清理我的项目,但没有解决。有什么想法吗?

static public func getBalance(_ balance_label: String) -> Int {
    let db = Firestore.firestore()
    let userId = Auth.auth().currentUser?.uid ?? ""
    let balanceRef = db.collection("account").document(userId).collection("balance")
    balanceRef.getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
            return 0
        } else {
            guard let querySnapshot = querySnapshot else { return 0 }
            for document in querySnapshot.documents {
                print("document.data() is \(document.data())")
                guard let label = document.data()["label"] as? String else { continue }
                if label == balance_label {
                    guard let balance = document.data()["balance_amount"] as? Int else { return 0 }
                    return balance
                }
            }
            return 0
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我认为这是因为您的return语句位于第5行定义的闭包内:

balanceRef.getDocuments() { (querySnapshot, err) in ... }

该闭包的签名未指定返回类型,因此如果我认为如果您从该闭包内的return语句中删除值,然后确保在getDocuments() {}之后您显式返回一个Int您应该使编译器满意。

答案 1 :(得分:0)

getDocuments是一种异步方法。您不能return来自异步闭包的值。您将需要重构它以使用完成处理程序模式。

static public func getBalance(_ balance_label: String, completionHandler: @escaping (Int) -> Void) {
    let db = Firestore.firestore()
    let userId = Auth.auth().currentUser?.uid ?? ""
    let balanceRef = db.collection("account").document(userId).collection("balance")
    balanceRef.getDocuments { querySnapshot, err in
        guard let querySnapshot = querySnapshot, err == nil else {
            print("Error getting documents:", err ?? "Unknown error")
            completionHandler(0)
            return
        }

        for document in querySnapshot.documents {
            print("document.data() is \(document.data())")
            if let label = document.data()["label"] as? String, label == balance_label {
                let balance = document.data()["balance_amount"] as? Int
                completionHandler(balance ?? 0)
                return
            }
        }
        completionHandler(0)
    }
}

然后这样称呼它:

Foo.getBalance(label) { value in
    // use `value` here
}

// but not here, because the above runs asynchronously
//