https://kotlinlang.org logo
d

david.bilik

09/19/2022, 9:14 AM
hey, I have this class
Copy code
sealed class State<out T> {

    object Loading : State<Nothing>()
    data class Error(val error: Throwable) : State<Nothing>()
    data class Loaded<out T>(val data: T) : State<T>()
}
in my shared kotlin code, then I have a viewmodel emitting these different states during async call. Now I want to check in my iOS swift code for a type of a State so I can either show loading/loaded/error views but I have a hard time figuring out how to do this type check. The only way where my type check succeeds is for the
State.Loaded
, but for Error or Loading it shows a warning
Copy code
Cast from 'State<Character>' to unrelated type 'StateLoading' always fails
I suppose it’s because the Loading and Error does not have the type parameter, but how to do this properly?
n

Nicolas Patin

09/19/2022, 9:39 AM
Something like that should work ⬇️
Copy code
switch state {
case _ as State.Loading:
    // show loading
   break

case let state as State.Error:
    // show error
    let error = state.error

case let state as State.Loaded:
    // show loaded
    let data = state.data

default:
    fatalError("\(state) is not handled yet.")
}
You should have a dot between State and Loading/Error/Loaded 🤔
d

david.bilik

09/19/2022, 9:47 AM
it’s apparently not 1:1 translated from Kotlin to swift like this,
State.Loaded
is not recognized and when I open the generated code for eg. loading state it looks like this
Copy code
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("StateLoading")))
@interface SharedStateLoading : SharedState<SharedKotlinNothing *>
+ (instancetype)alloc __attribute__((unavailable));
+ (instancetype)allocWithZone:(struct _NSZone *)zone __attribute__((unavailable));
+ (instancetype)loading __attribute__((swift_name("init()")));
@property (class, readonly, getter=shared) SharedStateLoading *shared __attribute__((swift_name("shared")));
@end;
o

okarm

09/19/2022, 9:55 AM
Sealed classes are a known and long standing pain point. There are a few projects out there that aim to ease the pain. I'll try and find some to link here
s

Seb Jachec

09/19/2022, 9:57 AM
https://github.com/icerockdev/moko-kswift Looks pretty good. It’s something we’d really like to use (but currently is flooding the project with unnecessary warnings when we test – your mileage may vary)
n

Nicolas Patin

09/19/2022, 10:01 AM
@david.bilik that’s how I use my sealed class in my iOS projects for 2 years 🤔
d

david.bilik

09/19/2022, 10:02 AM
thanks guys, I did not realize the sealed classes are the problem, once I google i can find some relevant posts. Thanks!
54 Views