如何在 SwiftUI 视图中使用可能引发错误的函数?

问题描述 投票:0回答:1

我有一个实用函数,可以将数据保存到

CoreData

func saveData(content: String) throws {
    // saves a model to CoreData
}

我想在用户点击

Button
时触发此功能。类似的东西

Button(action: saveData)

但是当我尝试这样做时,我收到错误

Invalid conversion from throwing function of type '() throws -> Void' to non-throwing function type '() -> Void'

是否可以做我想象的事情,或者我应该做一些其他最佳实践?

ios swift swiftui
1个回答
1
投票
@State private var showError = false

Button(action: {
    do {
        try saveData()
    } catch {
        showError = true
    }
}, label: {
    ...
})

然后使用 .alert 修饰符显示错误

© www.soinside.com 2019 - 2024. All rights reserved.