使用Codable的Swift Rest API调用示例 [英] Swift Rest API call example using Codable

查看:44
本文介绍了使用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 = "https://jsonplaceholder.typicode.com/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 = "https://jsonplaceholder.typicode.com/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调用示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆