Warm tip: This article is reproduced from stackoverflow.com, please click
swift

best practice to escape from guard/let overuse and optionals

发布于 2020-03-27 10:22:05

I'm finding my code absolutely littered with optionals and guard/let statements.

An example is that I have an object that is filled over the course of a few VCs, so the variables in the object are optionals. When I go to use the whole request in a function though, it leads to ridiculous stuff like this:

func save(request: Request, completion: @escaping WebServiceResponse){
        guard let description = request.description,
            let totalAmount = request.totalAmount,
            let reserveAmount = request.reserveAmount,
            let holdingPeriod = request.holdingPeriod,
            let sender = request.sender,
            let receiver = request.receiver
            else {
                return
        }
        apiRequest(endpoint: apiEndpoint.Deal, path: "/save", body:
            [
                "description" : description,
                "total": totalAmount,
                "reserve": reserveAmount,
                "period":holdingPeriod,
                "from":sender,
                "to":receiver
            ], completion: completion)
    }

I'm finding these issues throughout my code whenever I use optionals, especially when I use optionals in a class object.

One answer suggested that I add further complexity to check if the method had been set... that would make my code even more unreadable. Is there any way to batch unwrap a class? Or maybe use a try/catch?

How can I improve?

Questioner
Code Wiget
Viewed
108
Rob Napier 2019-07-03 23:30

This is a "builder" problem, and it has a few solutions.

One is to separate mutable vs immutable structures. Build this up with a mutable RequestBuilder that has var optional values. Then, when it's complete, convert that to an immutable Request, that has let non-optional values. This will force you to do this giant if-let one time, but then it'll be done.

Another is to give all the values default values. As a rule, collections (including Strings) should not be optional. Just make them empty.