You are currently viewing How can I access the Kotlin Result type from Swift in a KMM project?

How can I access the Kotlin Result type from Swift in a KMM project?

I’ve working on a simple Kotlin Multiplatform project that target iOS and Android. I have a Repository class for combining the data from the network and local database. and I would like to expose this data through my shared module as a suspending functions with the Result type like so:

 commonMain/ override suspend fun getPokemonSpecies(id: Int): Result<PokemonSpecies> { return local.getPokemonSpecies(id).recoverCatching { val species = remote.getPokemonSpecies(id).getOrThrow() local.savePokemonSpecies(species).getOrThrow() } }

However, in my Swift ViewModel the suspending function’s callback resolves with an

Any?

type. I can print this data and it looks correct in the console, but can’t use the value as anything other than an

Any?

. I’ve tried casting to

Result

but

[Pokemon]

but to no avail. Is this use case supported or should I just fallback to throwing exceptions/writing a custom ResultType?

 iosApp/ func loadPokemon() { pokemonRepo.getPokemonPage(page: 0) { pokemon, error in if (pokemon != nil) { print(pokemon!) // prints Success([Pokemon(...), ...]) self.pokemonResult = .success(pokemon!) // fails because this is type Any } else { self.pokemonResult = .failure(error ?? ...) } } }

submitted by /u/fegan104
[link] [comments]