Wouter De Vos
09/20/2023, 1:10 PMclass ViewModel: ObservableObject {
@Published var phrases: [String] = ["Loading..."]
init() {
Greeting().greet { greeting, error in
DispatchQueue.main.async {
if let greeting = greeting {
self.phrases = greeting
} else {
self.phrases = [error?.localizedDescription ?? "error"]
}
}
}
}
}
However, in Xcode I get the errors in the photo attached. I have an idea of what’s going on here but my Swift is really rusty and I’m just trying to get through this tutorial without going down a Swift rabbit hole. Is there a simple fix for this that I might be missing? At the moment I can see that the greet
function in the Kotlin code does not have a lambda so I suspect that is why the compiler in Xcode is showing an error for that part. The second error with the type casting I’m unsure of. Are there some errors in the tutorial that I should be aware of?Wout Werkman
09/20/2023, 2:51 PMasync
functions. Before that, it used to be translated to a callback by Kotlin/Native.
I think what you can do is call await Greeting().greet()
and additionally wrap it in Task { ... }
to get in async scope.
Some inspiration:
class ViewModel: ObservableObject {
@Published var phrases: [String] = ["Loading..."]
init() {
Task {
if let greeting = try? await Greeting().greet() {
self.phrases = greeting
} else {
self.phrases = ["error"]
}
}
}
}