【问题标题】:Thread 4: Fatal error: 'try!' expression unexpectedly raised an error线程 4:致命错误:“尝试!”表达式意外引发错误
【发布时间】:2021-10-06 15:13:00
【问题描述】:

我正在尝试学习在 swiftUI 中进行 API 调用,我正在学习下一个教程 https://www.youtube.com/watch?v=1en4JyW3XSI 但代码给了我一个我找不到解决方案的错误。

PostList.swift

import SwiftUI

struct PostList: View {
    
    @State var posts: [Post] = []
    
    var body: some View {
        List(posts) { post in
            Text(post.title)
                
        }
        .onAppear(){
            Api().getPosts { (posts) in
                self.posts = posts
            }
        }
    }
}

struct PostList_Previews: PreviewProvider {
    static var previews: some View {
        PostList()
    }
}

Data.swift

import SwiftUI

struct Post: Codable, Identifiable {
    var id = UUID()
    var title: String
    var body: String
}

class Api{

    func getPosts(completition: @escaping([Post]) -> ()){
        guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else { return }
        
        URLSession.shared.dataTask(with: url) { (data, _, _) in
            let posts = try! JSONDecoder().decode([Post].self, from: data!)
            
            DispatchQueue.main.async {
                completition(posts)
            }
           
        }
        .resume()
    }
}

我得到的错误在这里let posts = try! JSONDecoder().decode([Post].self, from: data!),它是下一个:

线程 4:致命错误:“尝试!”表达式意外引发错误: Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "索引 0", intValue: 0), CodingKeys(stringValue: "id", intValue: nil)], debugDescription: "期望解码字符串但找到一个数字 而是。”,基础错误:无))

我注意到教程中的那个人使用了let id = UUID(),但这也给我带来了一个问题,我被要求将其更改为var id = UUID()

很抱歉,如果这是一个非常简单或愚蠢的问题,我只是想不出办法。

【问题讨论】:

    标签: json swift xcode api swiftui


    【解决方案1】:

    您可以通过添加 try - catch 块来查看确切的问题。

    这样

    URLSession.shared.dataTask(with: url) { (data, _, _) in
        do {
            let posts = try JSONDecoder().decode([Post].self, from: data!)
            
            DispatchQueue.main.async {
                completition(posts)
            }
            
        } catch {
            print(error.localizedDescription)
        }
    }
    

    所以现在错误是打印

    The data couldn’t be read because it isn’t in the correct format.
    

    这意味着你正在解码错误的类型。

    问题来了

    struct Post: Codable, Identifiable {
        var id = UUID() //< Here
    

    这里的 json id 有 Int 类型,而您使用的是 UUID 类型。

    所以只需将数据类型 UUID 更改为 Int。像这样

    struct Post: Codable, Identifiable {
        var id : Int //< Here
    

    【讨论】:

    • 这很有帮助,感谢您的解释。它有效,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    相关资源
    最近更新 更多