[Solved] Thread 4: Fatal error: ‘try!’ expression unexpectedly raised an error

Manuel Orozco Jimenez Asks: Thread 4: Fatal error: ‘try!’ expression unexpectedly raised an error
I’m trying to learn to make an API call in swiftUI, I’m following the next tutorial

but the code is giving me an error that I can’t find a solution for.

PostList.swift

Code:
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

Code:
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()
    }
}

The error that I’m getting is on here let posts = try! JSONDecoder().decode([Post].self, from: data!) and it’s the next:

Thread 4: Fatal error: ‘try!’ expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: “Index 0”, intValue: 0), CodingKeys(stringValue: “id”, intValue: nil)], debugDescription: “Expected to decode String but found a number instead.”, underlyingError: nil))

I have noticed that the guy in the tutorial uses let id = UUID() but that gives me a problem as well and I’m being asked to change it to var id = UUID().

I’m sorry if it’s a very simple or stupid question, I just can’t see to find a way around it.

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.