Swift Learning notes-control flow-early exit (guard)

Source: Internet
Author: User

Like a if statement, guard execution depends on the Boolean value of an expression. We can use guard statements to require that the condition must be true when the guard code is executed after the statement. Unlike if statements, a guard statement always has a else clause that executes the else code in the substation if the condition is not true.

Func Greet (person: [string:string]) {    guard-let name = person["name"] else {        return    }    print ("Hello \ (n AME) ")    guard Let location = person[' Location '] else {        print (" I hope the weather is nice near you. ")        Return    }    print ("I hope the weather is nice in \ (location).")} Greet (["Name": "John"])//prints "Hello john!" Prints "I hope the weather is nice near you." Greet (["Name": "Jane", "Location": "Cupertino"])//prints "Hello jane!" Prints "I hope the weather is nice in Cupertino."

If guard the condition of the statement is met, the code continues to execute after the enclosing curly brace of the protection statement ends. Any variable or constant that uses an optional binding as part of the condition and is assigned a value is available for the code snippet that appears for the remaining protection statements.

If the condition is not met, the code on the else branch will be executed. This branch must transfer control to exit guard the code snippet that appears in the statement. It can be used to control the transfer of statements such as return , break or continue do this, or it calls a method or function that does not return, for example fatalError() .

ifusing statements on demand guard improves the reliability of our code compared to statements that can implement the same functionality. It allows your code to be executed coherently without having to wrap it in a else block, which allows you to handle code that violates the requirements close to the requirements.

Swift Learning notes-control flow-early exit (guard)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.