Swift's guard keyword

前端 未结 13 2348
一整个雨季
一整个雨季 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:45

    When a condition is met using guard it exposes variables declared within the guard block to the rest of the code-block, bringing them into its scope. Which, as previously stated, will certainly come in handy with nested if let statements.

    Note that guard requires a return or a throw in its else statement.

    Parsing JSON with Guard

    Below is an example of how one might parse a JSON object using guard rather than if-let. This is an excerpt from a blog entry that includes a playground file which you can find here:

    How to use Guard in Swift 2 to parse JSON

    func parseJSONWithGuard(data : [String : AnyObject]) throws -> Developer {
    
        guard let firstname = data["First"] as? String  else {
            return Developer() // we could return a nil Developer()
        }
    
        guard let lastname = data["Last"] as? String else {
            throw ParseError.BadName // or we could throw a custom exception and handle the error
        }
    
        guard let website = data["WebSite"] as? String else {
            throw ParseError.BadName
        }
    
        guard let iosDev = data["iosDeveloper"] as? Bool else {
            throw ParseError.BadName
        }
    
    
    
        return Developer(first: firstname, last: lastname, site: website, ios: iosDev)
    
    }
    

    download playground: guard playground

    More info:

    Here's an excerpt from the The Swift Programming Language Guide:

    If the guard statement’s condition is met, code execution continues after the guard statement’s closing brace. Any variables or constants that were assigned values using an optional binding as part of the condition are available for the rest of the code block that the guard statement appears in.

    If that condition is not met, the code inside the else branch is executed. That branch must transfer control to exit the code block that that guard statement appears in. It can do this with a control transfer statement such as return, break, or continue, or it can call a function or method that doesn’t return, such as fatalError().

提交回复
热议问题