You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中如何在.onDelete里调用异步任务?

SwiftUI List 删除操作报错问题

我有一个包含User类型条目的SwiftUI List,已实现.onDelete方法,代码如下:

List {
    //foreach with id
    ForEach(usersListVM.users, id: \.id) { user in
        ResponsiveView { prop in
            UserCell(prop: prop, user: user)
        }
    }
    .onDelete { index in
        usersListVM.deleteUser(id: usersListVM.users[index.first!].id!)
    }
}

用于删除的API调用函数采用async/await语法:

func deleteUser(id: Int) async {
    try await userApi.deleteUser(id: id)
}

运行代码时出现错误:Invalid conversion from throwing function of type '(IndexSet) async throws -> Void' to non-throwing function type '(IndexSet) -> Void'


解决方法

问题核心是.onDelete的闭包不支持直接调用异步抛出函数,需做以下两处调整:

  1. 在.onDelete闭包内用Task包裹异步操作,并处理错误:
.onDelete { index in
    guard let userId = usersListVM.users[index.first!].id else { return }
    Task {
        do {
            try await usersListVM.deleteUser(id: userId)
        } catch {
            // 这里可以添加删除失败的处理逻辑,比如弹窗提示
            print("删除失败:\(error.localizedDescription)")
        }
    }
}
  1. 修正deleteUser函数,补上throws声明,并同步更新本地数据:
func deleteUser(id: Int) async throws {
    try await userApi.deleteUser(id: id)
    // 删除API调用成功后,同步更新本地用户列表,保证UI与数据一致
    if let removeIndex = users.firstIndex(where: { $0.id == id }) {
        users.remove(at: removeIndex)
    }
}

内容的提问来源于stack exchange,提问作者agmcoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 03:50:25