I have SwiftUI ContentView struct from which I call function in standard Swift class. This function may throw an error which I`d like to show via Alert in ContentView. Appearance of Alert is controlled by Bool @State var declared in ContentView. I was trying to use @Binding property wrapper in the function but it is obviously not correct. Should I rather use ObservableObject or what is the best approach? Thanks.
Fragment of ContentView with Alert
HStack {
Button("Load data...", action: {
let panel = NSOpenPanel()
panel.title = "Select CSV formatted data file"
panel.canChooseFiles = true
panel.allowedFileTypes = ["csv"]
panel.allowsMultipleSelection = false
panel.begin(completionHandler: {result in
if result == .OK {
getDataset(fromFileURL: panel.url!, withHeaderLine: headerLine)
}
})
})
.padding()
.alert(isPresented: $isError, content: {
Alert(title: Text("Error"), message: Text(errorText), dismissButton: .default(Text("OK")))
})
Toggle("With header line", isOn: $headerLine)
}.toggleStyle(SwitchToggleStyle())
}
Fragment of called function which can throw error
do {
var fromRow = 0
let fileContent = try String(contentsOf: fromFileURL)
let rows = fileContent.components(separatedBy: "\n")
if withHeaderLine { fromRow = 1 }
for i in fromRow...rows.count - 1 {
let columns = rows[i].components(separatedBy: ",")
guard let xValue = Double(columns[0]) else {
throw myError.conversionFailed
}
guard let yValue = Double(columns[1]) else {
throw myError.conversionFailed
}
myDataset.append(Dataset(x: xValue, y: yValue))
}
} catch myError.conversionFailed {
errorText = "Value conversion to Double failed."
isError.toggle()
} catch let error {
errorText = error.localizedDescription
isError.toggle()
}
}