swift - 如何转换 '(Data?, URLResponse, Error?) to expected argument type '(数据?、URLResponse?、错误?)-> Void'

标签 swift xcode swift5

我不明白为什么我在这一行中遇到 { 错误。让任务 = URLSession

let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse, error: Error?) in   //ERROR: Cannot convert value of type '(Data?, URLResponse, Error?) -> ()' to expected argument type '(Data?, URLResponse?, Error?) -> Void'

        self.removeActivityIndicator(activitiyIndicator: myActivityIndicator)

        if error != nil {
            self.displayMessage(userMessage: "Could not successfully perform this request")
            print("error=\(String(describing: error))")
            return
        }

        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

如有任何建议,我们将不胜感激。

最佳答案

请仔细阅读错误,它表示第二个闭包参数 (URLResponse) 必须是可选的 (URLResponse?)

let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

但是不需要注释参数类型

let task = URLSession.shared.dataTask(with: request) { data, response, error in

如果您错误地对待(可选)类型,编译器会提示。

并且不要在 Swift 中使用 NS.. 集合类型。使用 native 类型。

关于swift - 如何转换 '(Data?, URLResponse, Error?) to expected argument type '(数据?、URLResponse?、错误?)-> Void',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61126698/

相关文章:

ios - 过滤唯一值以在消息收件箱中显示唯一用户名

c++ - GCC/XCode 等同于 _CrtCheckMemory?

ios - Xcode 8 : Auto Layout Issue

ios - 使用 AlamofireObjectMapper 将对象 json 数据映射到 2 个单独的数组中

ios - shouldChangeCharactersInRange 接受单个 '.'

ios - Swift - 创建一个没有导航 Controller 的后退按钮

swift - SwiftUI 分段选择器的问题

ios - 更新后错误 : . ..异常 'NSGenericException' ,原因: 'This coder requires that replaced objects be returned from initWithCoder:'

ios - 快速获取用户的联系人电话号码

swift - 如何从 Swift 中的段落开始到 UITextView