Hi all, apologies if I mess something up in this pitch. I've not ever contributed to the Swift forums before.
The introduction of the Result type into the standard language in SE-0235 is one of my favorite features when building libraries. When a user of a returned Result would like to evaluate it... it usually looks a bit like this:
let result: Result<Data, MyCustomError> = getResult()
switch result {
case .success(let data):
// Do something with the data here
case .failure(let error):
// Handle error
}
Which is fine for most cases. However, in the event we need to cascade multiple results, it can get a bit ugly.
For example:
let firstResult: Result<Data, MyCustomError> = getFirstResult()
switch firstResult {
case .success(let data):
let secondResult: Result<Data, MyCustomError> = getSecondResult(using: data)
switch secondResult {
case .success(let secondData):
// Do something with secondData
case .failure(let secondError):
// Handle secondError
}
case .failure(let firstError):
// Handle firstError
}
Which, as you can see, gets a bit heavy with the nested switching. This often reminds me of nested if
statements, and as a “Never Nester” I would typically fall back on the guard
keyword here. I think that the guard
keyword would be very useful for evaluating Result types too - however as it works right now the guard
keyword has a problem with Results…
let firstResult: Result<Data, MyCustomError> = getFirstResult()
guard case .success(let data) = firstResult else {
// Handle first error - But no reference to firstError!
return
}
let secondResult: Result<Data, MyCustomError> = getSecondResult(using: data)
guard case .success(let secondData) = secondResult else {
// Handle second error - But no reference to secondError!
return
}
As the comments suggest, I don’t have reference to the error type in the else
portion of the guard
statement. As far as I can tell, there’s no way to have this syntax and have access to the returned error type.
Perhaps there’s some way to have this functionality by either expanding the guard
statement or by updating the Result type?
So thats why I’m making this pitch. I’m not 100% sure what the fix is or should be. I’m not even sure if this is a useful change to the language or something that other users of Swift want - but let’s discuss that here!
Thank you for taking the time to read this.