Swift's guard keyword

前端 未结 13 2258
一整个雨季
一整个雨季 2020-11-27 09:03

Swift 2 introduced the guard keyword, which could be used to ensure that various data is configured ready to go. An example I saw on this website demonstrates a

相关标签:
13条回答
  • 2020-11-27 10:09

    When to use guards

    If you’ve got a view controller with a few UITextField elements or some other type of user input, you’ll immediately notice that you must unwrap the textField.text optional to get to the text inside (if any!). isEmpty won’t do you any good here, without any input the text field will simply return nil.

    So you have a few of these which you unwrap and eventually pass to a function that posts them to a server endpoint. We don’t want the server code to have to deal with nil values or mistakenly send invalid values to the server so we’ll unwrap those input values with guard first.

    func submit() {
        guard let name = nameField.text else {
            show("No name to submit")
            return
        }
    
        guard let address = addressField.text else {
            show("No address to submit")
            return
        }
    
        guard let phone = phoneField.text else {
            show("No phone to submit")
            return
        }
    
        sendToServer(name, address: address, phone: phone)
    }
    
    func sendToServer(name: String, address: String, phone: String) {
      ...
    }
    

    You’ll notice that our server communication function takes non-optional String values as parameters, hence the guard unwrapping beforehand. The unwrapping is a little unintuitive because we’re used to unwrapping with if let which unwraps values for use inside a block. Here the guard statement has an associated block but it’s actually an else block - i.e. the thing you do if the unwrapping fails - the values are unwrapped straight into the same context as the statement itself.

    // separation of concerns

    Without guard

    Without using guard, we’d end up with a big pile of code that resembles a pyramid of doom. This doesn’t scale well for adding new fields to our form or make for very readable code. Indentation can be difficult to follow, particularly with so many else statements at each fork.

    func nonguardSubmit() {
        if let name = nameField.text {
            if let address = addressField.text {
                if let phone = phoneField.text {
                    sendToServer(name, address: address, phone: phone)
                } else {
                    show("no phone to submit")
                }
            } else {
                show("no address to submit")
            }
        } else {
            show("no name to submit")
        }
    }
    

    Yes, we could even combine all these if let statements into a single statement separated with commas but we would loose the ability to figure out which statement failed and present a message to the user.

    https://thatthinginswift.com/guard-statement-swift/

    0 讨论(0)
提交回复
热议问题