Get your own website
Demo.swift
ContentView.swift
App.swift
 
import SwiftUI
import Foundation

struct NoteDTO: Decodable, Identifiable { let id: Int; let title: String; let body: String }

enum API {
  static func fetchNotes() async throws -> [NoteDTO] {
    let url = URL(string: "https://jsonplaceholder.typicode.com/posts?_limit=3")!
    let (data, _) = try await URLSession.shared.data(from: url)
    return try JSONDecoder().decode([NoteDTO].self, from: data)
  }
}

@MainActor
final class NotesViewModel: ObservableObject {
  @Published var notes: [NoteDTO] = []
  func loadFromAPI() async {
    do { notes = try await API.fetchNotes() }
    catch { print(error) }
  }
}

struct NotesView: View {
  @StateObject private var vm = NotesViewModel()
  var body: some View {
    List(vm.notes) { n in Text(n.title) }
      .task { await vm.loadFromAPI() }
  }
}

                    
import SwiftUI

struct ContentView: View {
  var body: some View {
    NotesView()
  }
}

                    
import SwiftUI

@main
struct MyApp: App {
  var body: some Scene {
    WindowGroup { ContentView() }
  }
}