Bradleycorn
06/18/2024, 9:17 PMsuspend functions and Swift ...
Note: I'm using SKIE in my project.
So, if i have a basic suspend function:
suspend fun doStuff(value: int) {
delay(100.milliseconds)
print("Did stuff with $value!)
}
I know the Swift side will get a cancelation error if the task/coroutine is canceled. And I can handle the error as an optional value in Swift, in order to "ignore" the cancelation exception:
Task {
try? await doStuff()
}
So far so good. But say my suspend function can throw some "custom" exception (other than a cancelation exception).
I want the Swift side to have to handle that error, but it would be nice if it could still "ignore" the cancelation exception.
Is there some way I can do that? Could I annotate my suspend function with @Throws() and only specify my "custom" exception?
@Throws(IllegalArgumentException::class)
suspend fun doStuff(value: int) {
delay(100.milliseconds)
if (value < 0) { throw IllegalArgumentException("Value must be greater than 0") }
print("Did stuff with $value!)
}
Or, maybe I'm misunderstanding the whole thing entirely.swanti
06/18/2024, 9:50 PMResult class so you don't deal with Exceptions, but instead deal with an Error type and a Success typePablichjenkov
06/18/2024, 9:52 PMTadeas Kriz
06/18/2024, 10:30 PMdo {
return try await doStuff()
} catch is CancellationError {
return nil
} catch {
// handle 'error' here
}Tadeas Kriz
06/18/2024, 10:33 PM@NullOnCancelled and @UnsafeCancellation where the first one would make your return type optional for Swift and return nil on cancellation and the second allowing you to handle cancellation yourself and crash if encountered