Silly question, for people with KMM/iOS experience...
# kotlin-native
a
Silly question, for people with KMM/iOS experience here. What is the best way to switch over kotlin sealed classes on iOS (if at all)?
Copy code
data class Payload(val name: String)

sealed class Event {
   
    class Inserted(val payload: Payload) : Event()
    
    class Updated(val payload: Payload) : Event()
    
    class UpdatedAll(val payloads: List<Payload>, val flag: Boolean) :
        Event()
}
p
Write an extension on the event containing 3 lambdas in it's signature
a
Can you give a short example?
p
fun<t> reduce(event : Event, insert: (Insert)-> T, updated: (Updated) -> T) : T return when event is Updated > updated (event) is Insert > insert(event)
It's not a silly question
👆 2
p
Copy code
switch event {
case is Inserted:
    let inserted = event as! Inserted
    // do something with inserted.payload
default:
    break
}
Would be the way to switch on it in swift.
s
You should be able to remove the ! by writing
Copy code
switch event {
case let inserted as Inserted:
    // do something
default:
   break
}
👀 2
p
True, that does work. Even better! Thanks.
a
Thanks everyone!
p
The code I posted is explicitly there to handle the exhaustiveness and omit a default block
p
And that’s cool and all but sometimes it’s also great to stick with native conventions. That’s one of the big positives with KMM. Share as much as possible but let the native devs do their thing the way they’re used to. Also, I think
when (SealedClass)
still compiles when you omit a case? It’s just a warning otherwise. So you’d still have to check KMM code to be sure it’s exhaustive. I still liked it. Wouldn’t have thought of that myself. 👍🏼
p
No, as of 1.6 that's an error