I’ve Finally Mastered Case Let In My Swift Code

Steven Curtis
3 min readSep 20, 2021

You know how you can always do things better in life. Certainly you can. I’ve previously created a micro-project around downloading a JSON String and writing the result to the screen.

There is nothing special going on in terms of the completion — I’m just returning a closure ((Users) -> Void)? which I guess is *fine* in some sense.

So..what gives?

Returning a Result type would give much greater flexibility. Why?

Well, we need to think about errors that are returned from the backend or whatever — in the original implementation we aren’t handling those errors.

That’s a little bit rubbish overall.

We can instead let the ViewModel return a closure

var closure: ((Result<Users, Error>) -> Void)?

which the viewModel can then use to process (instead of printing this we could write it to a UITextView, if we wrapped it in a DispatchQueue.main.async to make sure we would be on the main thread) although in this case we are printing out the result to the console.

An implementation of that might look something like the following:

--

--

Responses (2)