首页 > 解决方案 > 如何将 '(Data?, URLResponse, Error?) 转换为预期的参数类型 '(Data?, URLResponse?, Error?) -> Void'

问题描述

我不明白为什么我{在这一行出现错误。让任务 = 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

任何建议将不胜感激。

标签: swiftxcodeswift5

解决方案


请仔细阅读错误,它说第二个闭包参数(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

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

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


推荐阅读