无法将类型为 ‘[String: Any]’ 的值转换为 Swift 中闭包结果类型 ‘Void’。

huangapple go评论74阅读模式
英文:

Cannot convert value of type '[String : Any]' to closure result type 'Void' in Swift

问题

以下是您的代码的翻译部分:

有没有建议,为什么我的代码会返回错误(我已经提供了我创建的函数的详细信息,是什么导致了这个错误:

>无法将类型为'[String : Any]'的值转换为闭包结果类型'Void'

let tes = fetchUser(completionHandler: { baseData, error in
    if let baseData = baseData {
        let parm_key: String = baseData["parm_key"] as! String
        return baseData
    }
})
print(tes)


func fetchUser(completionHandler: @escaping ([String: Any]?, Error?) -> [String: Any]) {
            ...  
            let task = URLSession.shared.dataTask(with: request) { data, response, error in
                
                guard let data = data else { return }
                let stringData = String(data: data, encoding: .utf8)!
                let encryptedResult = stringData.data(using: .utf8)!
                
                if let data = Data(base64Encoded: encryptedResult) {
                    let firstDecoded = String(data: data, encoding: .utf8)!
                    let countDrop = Int(String(firstDecoded.prefix(2))) ?? 0
                    let base64EncodedData = firstDecoded.dropFirst(countDrop + 2)
                    if let secondData = Data(base64Encoded: String(base64EncodedData)) {
                        let secondDecoded = Data(String(data: secondData, encoding: .utf8)!.utf8)
                        do {
                            // 确保这个 JSON 是我们期望的格式
                            if let json = try JSONSerialization.jsonObject(with: secondDecoded, options: []) as? [String: Any] {
                                completionHandler(json, nil)
                            }
                        } catch let error as NSError {
                            print("加载失败:\(error.localizedDescription)")
                        }
                    }
                }
            }
            
            task.resume()
        }

请注意,代码中的return baseData可能会导致错误,因为fetchUser函数的闭包返回类型是([String: Any]?, Error?) -> [String: Any],而不是Void。您可能需要更改代码以适应函数的返回类型。

英文:

Any suggestion why my code return error( I already provide details of the function I've made what cause that error:

>Cannot convert value of type '[String : Any]' to closure result type 'Void'

let tes = fetchUser(completionHandler: { baseData, error in
    if let baseData = baseData {
        let parm_key : String = baseData["parm_key"] as! String
        return baseData
    }
})
print(tes)


func fetchUser(completionHandler: @escaping ([String:Any]?, Error?) -> [String:Any]) {
            ...  
            let task = URLSession.shared.dataTask(with: request) { data, response, error in
                
                guard let data = data else { return }
                let stringData = String(data: data, encoding: .utf8)!
                let encryptedResult = stringData.data(using: .utf8)!
                
                if let data = Data(base64Encoded: encryptedResult) {
                    let firstDecoded = String(data: data, encoding: .utf8)!
                    let countDrop = Int(String(firstDecoded.prefix(2))) ?? 0
                    let base64EncodedData = firstDecoded.dropFirst(countDrop + 2)
                    if let secondData = Data(base64Encoded: String(base64EncodedData)) {
                        let secondDecoded = Data(String(data: secondData, encoding: .utf8)!.utf8)
                        do {
                            // make sure this JSON is in the format we expect
                            if let json = try JSONSerialization.jsonObject(with: secondDecoded, options: []) as? [String: Any] {
                                completionHandler(json, nil)
                            }
                        } catch let error as NSError {
                            print("Failed to load: \(error.localizedDescription)")
                        }
                    }
                }
            }
            
            task.resume()
        }

答案1

得分: 1

完成处理程序闭包接受两个参数,但不返回任何值。您需要删除return行,并可能更新闭包外部范围中的另一个变量以获取所需的值。该错误意味着该函数不期望返回任何内容(void),但却返回了一个字典(baseData)。

在您的示例中,tes 是否具有您需要的值?如何处理这个问题将取决于fetchUser()的定义方式,但它可能不会直接返回值。您必须将其分配给完成处理程序中的某个东西。

var returnedBaseData = [String:Any]()

fetchUser(completionHandler: { baseData, error in
    if let baseData = baseData {
        returnedBaseData = baseData
    }
})
英文:

The completion handler closure takes two arguments but does not return a value. You need to remove the return line and perhaps update another variable (in the scope outside the closure) with the needed value. The error means that the function is not expecting to return anything (void), yet a dictionary (baseData) is returned.

In your example, does tes have the value you need? How to handle this will depend on how fetchUser() is defined, but it probably doesn’t return the value directly. You must assign it to something in the completion handler.

var returnedBaseData = [String:Any]()

fetchUser(completionHandler: { baseData, error in
    if let baseData = baseData {
        returnedBaseData = baseData
    }
})

huangapple
  • 本文由 发表于 2023年8月10日 09:17:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76872091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定