Swift's guard keyword

前端 未结 13 2340
一整个雨季
一整个雨季 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 09:57

    Simply put, it provides a way to validate fields prior to execution. This is a good programming style as it enhances readability. In other languages, it may look like this:

    func doSomething() {
        if something == nil {
            // return, break, throw error, etc.
        }
        ...
    }
    

    But because Swift provides you with optionals, we can't check if it's nil and assign its value to a variable. In contrast, if let checks that it's not nil and assigns a variable to hold the actual value. This is where guard comes into play. It gives you a more concise way of exiting early using optionals.

提交回复
热议问题