Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force passing a single parameter, to a multi-optional-parameter function

Tags:

swift

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?

like image 630
Beau Nouvelle Avatar asked Dec 18 '22 10:12

Beau Nouvelle


1 Answers

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.

like image 136
Yannick Avatar answered May 10 '23 15:05

Yannick