swift - 如何将 '(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
任何建议将不胜感激。
解决方案
请仔细阅读错误,它说第二个闭包参数(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 中使用集合类型。使用本机类型。
推荐阅读
- iis-10 - Windows Server 2022--IIS 无法修改文件共享
- c# - 在不同的时间速率下将耐用性降至 0?
- typescript - 类型“{}”上不存在属性“title”。TS2339
- python - SQLAlquemy:仅当特定项目不存在时才插入
- flutter - 将 ListView 的容器自定义为所需的结果
- javascript - '装饰器函数内设置的对象属性不会按预期持续存在。'
- opentok - OpenTok 归档到 Microsoft OneDrive
- c++ - Ubuntu上的vcpkg和cmake和vsc找不到包
- tableau-api - 如何在 datetrunc 中获取上一年的值?
- ansible - 使用条件渲染时出现Ansible模板奇怪错误