Consider following function:
func myFunction(completion: (data: Data?, error: Error?) -> ()) { }
My current requirement would be to have completion:
only accept either a data
value or error
value, but not both. One must be nil.
It's easy enough to just keep them both as optional then unwrap and check their values later, but I think it would be better if the compiler was able to inform the developer that they can't set both.
Looking at it from the other way, knowing that one of them will always be set to someValue
would be even more useful.
This way you could guarantee that you'll get an error
or data
, and never have to worry about handling cases where they're both nil
.
Is there currently a way to do this?
I would suggest you use an enum like this
enum Result<T> {
case Success(T)
case Error(String, Int)
}
Have a look at Best way to handle errors from async closures in Swift 2? where the original answer is written in more detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With