How would you switch case with a swift optional + handle both success and error cases?
j
Javier
12/29/2020, 6:07 PM
Maybe a fold function based on callbacks, Kotlin usage:
someResult.fold(
success = { data -> doSomething(data) },
error = { message -> println(message) },
)
s
Sam
12/29/2020, 11:05 PM
To
switch
over a sealed class you can use:
Copy code
switch result{
case let success as ResultSuccess:
print("success")
case let failure as ResultFailure:
print("failure")
default:
break //Swift will require an exhaustive switch
}
I think but am not positive that you could include type parameters on those
let
lines.
👍 2
j
Joaquim Ley
12/30/2020, 12:57 PM
Thank you @Sam@Javier for your input(s) I’ll try it out and give some feedback here 🙏
Joaquim Ley
12/30/2020, 4:01 PM
It worked @Sam, your implementation works 😉
Followup Q have you gotten sealed class working correctly with Swift?
For some context, I have a ViewState that has various class (Loading, Idle, Success etc.) as a sealed class, but now when I declare a variable as a ViewState I can’t set it
s
Sam
12/30/2020, 4:30 PM
I haven’t run into that issue. Have a look at your module header (cmd+click on a Kotlin class in a Swift file to easily get there) and verify that your sealed classes are show as inheriting from the base sealed class. Something like: