SWIFTUI:来自 'async' 类型 '(IndexSet) async 的函数的无效转换

SWIFTUI: Invalid conversion from 'async' function of type '(IndexSet) async

我正在学习 SWIFTUI 并尝试做一些应用程序来测试我的知识,但实际上没有遵循教程,因为我喜欢思考为什么事情会以某种方式工作。这就是我学习的方式:)

所以,我试图通过 API 调用一个函数来 post 一些数据。该方法位于 ViewModel 内部。视图是一个列表,我需要能够触发 .OnDelete 修饰符以通过视图模型触发 API 调用。

但我总是遇到错误:

Invalid conversion from 'async' function of type '(IndexSet) async -> Void' to synchronous function type '(IndexSet) -> Void'

这是代码。

在ContentView.swift中:

        // there is a @State var res = PostsViewModel() above the body!
    List { 
        ForEach(res.posts, id:\.self){ item in
            VStack {
                Text(item.title) 
                    .font(.headline)
                Text("\(item.content) <> \(item._id)")
            }
            
        }
        .onDelete{ IndexSet in
                var index: Int = -1
                for idx in IndexSet {
                    index = idx
                }
                print("index ix \(index)")

                 await res.updateData(at: index)
                

        }

    }

在PostViewModel.swift中:

    func updateData(at index: Int) async {
        let item = posts[index]
        print(item._id)
        guard let url = URL(string: "{URL HERE HIDDEN}/api/posts/\(item._id)") else {
            print("Error: cannot create URL")
            return
        }
        struct UploadData: Codable {
            let title: String
            let content: String
        }
        
        // Add data to the model
        let uploadDataModel = UploadData(title: "Hello", content: "World!!")
        
        // Convert model to JSON data
        guard let jsonData = try? JSONEncoder().encode(uploadDataModel) else {
            print("Error: Trying to convert model to JSON data")
            return
        }
        // Create the request
        var request = URLRequest(url: url)
        request.httpMethod = "PUT"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        do {
            guard let (data, _) = try? await URLSession.shared.upload(for: request, from: jsonData) else {
                 print("failed to connect")
                return
            }

            guard let decodedOrder = try JSONDecoder().decode(PostsModel?.self, from: data) else {
                 print("failed to decode")
                return
            }
                print(decodedOrder.content)
                
            } catch {
                print("Checkout failed.")
                return
            }
}

我做错了什么?

将异步函数包装在 Task

Task {
    await res.updateData(at: index)
}

如果 PostsViewModel 是一个 class 声明一个 @StateObject

@StateObject var res = PostsViewModel()