使用Codable的Swift Rest API调用示例

编程入门 行业动态 更新时间:2024-10-11 19:20:11
本文介绍了使用Codable的Swift Rest API调用示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在跟踪有关使用Swift和Codable进行REST API调用的教程.尽管我在键入所有内容时都非常小心,但是我无法编译以下内容.谁能告诉我怎么了?另外,有人可以给我指出一个更好的教程吗?错误是:

I am following a tutorial on REST API calls with Swift and Codable. I cannot compile the following although I was careful when I typed all of it. Can anyone tell me what's wrong? Also, can anyone point me to a better tutorial? The error is:

捕获块无法访问

还有

在范围内找不到json

cannot find json in scope

import UIKit import Foundation struct Example: Codable { let userId: Int let id: Int let title: String let completed: Bool } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } func getJson(completion: @escaping (Example)-> ()) { let urlString = "jsonplaceholder.typicode/todos/1" if let url = URL(string: urlString) { URLSession.shared.dataTask(with: url) {data, res, err in if let data = data { let decoder = JSONDecoder() do { let json: Example = try! decoder.decode(Example.self, from: data) completion(json) }catch let error { print(error.localizedDescription) } } }.resume() } } getJson() { (json) in print(json.id) } }

推荐答案

您可以使用"guard let"代替"do catch"

Instead of "do catch", you can use "guard let"

func getJson(completion: @escaping (Example)-> ()) { let urlString = "jsonplaceholder.typicode/todos/1" if let url = URL(string: urlString) { URLSession.shared.dataTask(with: url) {data, res, err in guard let data = data else {return print("error with data")} let decoder = JSONDecoder() guard let json: Example = try? decoder.decode(Example.self, from: data) else {return print("error with json")} completion(json) }.resume() } }

这不会不处理错误,所以我的解决方案只是解决您的问题,而不是针对所有类似情况的通用解决方案.

This does NOT handle errors, so my solution is just to an answer to your question, not a general solution for every similar cases.

更多推荐

使用Codable的Swift Rest API调用示例

本文发布于:2023-11-26 04:25:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632620.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:示例   Swift   Codable   API   Rest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!