我如何将这个新的 get 方法用于其他模型?

How can i use this new get method for other models?

class Network {
    func getingData(completion : @escaping ([Model]) -> ()) async {
        guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else { return }
        do {
            let (data, _) = try await URLSession.shared.data(from: url)
            if let posts = try? JSONDecoder().decode([Model].self, from: data) {
                completion(posts)
            }
        }
        catch {
            print("error")
        }
    }
}

是您要找的吗?

import Foundation

class Network {

  func getingData<Model: Decodable>(completion : @escaping ([Model]) -> ()) async {
    guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else {
      return
    }
    do {
      let (data, _) = try await URLSession.shared.data(from: url)
      if let posts = try? JSONDecoder().decode([Model].self, from: data) {
        completion(posts)
      }
    } catch {
      print("error")
    }
  }

}

如果是这样,您只需将 Model 类型声明为泛型即可。您唯一需要 Model 符合的是 DecodableJSONDecoder().decode([Model].self, from: data) 调用的要求)。

您可以尝试类似这种方法,其中 getDataDecodable 一起使用,如上一个答案中所述。 在此特定示例中,数组 Decodable.

struct Post: Decodable, Identifiable {
    let userId: Int
    let id: Int
    let title: String
    let body: String
    var comments: [Comment]?
}

struct Comment: Decodable, Identifiable {
    let postId: Int
    let id: Int
    let name: String
    let email: String
    let body: String
}

struct ContentView: View {
    let client = Network()
    @State var posts: [Post] = []  
    
    var body: some View {
        List {
            ForEach(posts, id: \.id) { post in
                Text(post.title)
            }
        }
        .task {
            posts = await client.getData(from: "https://jsonplaceholder.typicode.com/posts")
            // all comments from the first post
            let comments: [Comment] = await client.getData(from: "https://jsonplaceholder.typicode.com/posts/\(posts[0].id)/comments")
            print("\n---> comments: \(comments)")
        }
    }
}

class Network {

    func getData<T: Decodable>(from urlString: String) async -> [T] {
        guard let url = URL(string: urlString) else {
            print(URLError(.badURL))
            return [] // <-- todo, deal with errors
        }
        do {
            let (data, response) = try await URLSession.shared.data(for: URLRequest(url: url))
            guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
                print(URLError(.badServerResponse))
                return [] // <-- todo, deal with errors
            }
            let results = try JSONDecoder().decode([T].self, from: data)
            return results
        }
        catch {
            return [] // <-- todo, deal with errors
        }
    }
    
}