线程 4:致命错误:“尝试!” 表达式意外地引发了错误

Man*_*nez -1 api xcode json swift swiftui

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

帖子列表.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()
    }
}
Run Code Online (Sandbox Code Playgroud)

数据.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()
    }
}
Run Code Online (Sandbox Code Playgroud)

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

线程 4:致命错误:“尝试!” 表达式意外引发错误: Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "id", intValue: nil) )],debugDescription:“预期解码字符串,但发现了一个数字。”,underlyingError:nil))

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

如果这是一个非常简单或愚蠢的问题,我很抱歉,我只是看不到找到解决方法。

Raj*_*han 6

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

\n

像这样

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

所以现在打印出错误:

\n
\n

无法读取数据\xe2\x80\x99,因为它的格式\xe2\x80\x99t 不正确。

\n
\n

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

\n

问题就在这里

\n
struct Post: Codable, Identifiable {\n    var id = UUID() //< Here\n
Run Code Online (Sandbox Code Playgroud)\n

这里的 json id 具有 Int 类型,并且您正在使用UUID类型。

\n

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

\n
struct Post: Codable, Identifiable {\n    var id : Int //< Here\n
Run Code Online (Sandbox Code Playgroud)\n