https://kotlinlang.org logo
#announcements
Title
# announcements
c

Cdev

03/22/2021, 7:55 PM
I have a KMM project with Sealed classes and classes inside of those, to represent some state. On the Kotlin side it's idiomatic to use a "when" statement on these. On the swift side the best I could come up with were switch statements and it doesn't seem to realize that my cases are exhaustive and instead requires me to add a "default:" case. Is this a limitation of the what KMM sealed classes compile down to in their Swift interop? let menuStyle = projectConfig.settings.appearance.menuStyle       switch menuStyle {       case (is Settings.AppearanceMenuStyleBottom):         print("Bottom Menu")         break       case (is Settings.AppearanceMenuStyleSlideOut):         print("SlideOut Menu")         break       case (is Settings.AppearanceMenuStyleTiled):         print("Tiled Menu")         break       default: print("Swift requires this even though the sealed class is exhausted")       }
e

ephemient

03/22/2021, 8:16 PM
that being said, even if it is exhaustive, Swift will force you to write a
@unknown default:
in case of library changes, unless the enum is "frozen" which I don't think Kotlin supports yet https://useyourloaf.com/blog/swift-5-frozen-enums/
c

Cdev

03/22/2021, 8:23 PM
Oh cool thank you very much, I did not know about either of things.
d

darkmoon_uk

03/23/2021, 1:42 AM
I'll be that annoying guy this time, who questions why you even want to switch on your sealed state in Swift 🙂 I'm also in the midst of a KMM project and for us this wouldn't come up because, while we do also use sealed classes heavily to represent states (great aren't they?), this stays within the shared presentation logic and never leaks into each platform specific view layer. In the interest of keeping the view layer as thin and as dumb as possible; our view models spell-out the presentation in terms of the individual strings, booleans, and numbers that are required to drive the on screen widgets. Even de-structuring a state in the view is a no-no. In this way the Swift side is only ever really collecting `Flow`s of primitive values, and calling back Kotlin functions of user interactions with the same. Appreciate all use cases are different and you may have your own good principles for doing this - just throwing it out there in case it helps!
c

Cdev

03/23/2021, 3:17 PM
@darkmoon_uk Sure yeah I agree with what you said. For my case I am taking a kinda unwieldy response from the server and am trying to get rid of my Enums and turn them into the Classes themselves since for example the first item in my enum might map to a type with just a String and the second item in the enum might have map to a type that has a String, Int, SizeType. Danny Preussler's KotlinConf talk was my original inspiration and if I understand it correctly there's also a lot of benefit in doing this on the non-state side as well:

https://www.youtube.com/watch?v=t3DBzaeid74

195 Views