https://kotlinlang.org logo
#getting-started
Title
# getting-started
w

Wouter De Vos

09/20/2023, 1:10 PM
Hi there! I’m following along the tutorial for Kotlin Multiplatform for iOS and Android. I’m on step 4. Upgrade your app. The tutorial instructs you to add the following logic to the view model in iOS:
Copy code
class 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?
w

Wout Werkman

09/20/2023, 2:51 PM
This tutorial probably assumes Swift < 5.5. Since Swift 5.5, suspend functions are translated to
async
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:
Copy code
class ViewModel: ObservableObject {
    @Published var phrases: [String] = ["Loading..."]
    init() {
        Task {
            if let greeting = try? await Greeting().greet() {
                self.phrases = greeting
            } else {
                self.phrases = ["error"]
            }
        }
    }
}
2 Views