Swift's Boolean

Source: Internet
Author: User

Swift has an underlying boolean type called BOOL. Boolean values are also known as logical values, because their values are only ture or false. Swift provides two Boolean constants, True and false:

Let Orangesareorang = True

Let turnipsaredelicious = False

The types of Orangesareorange and Turnipsaredelicious are Boolean and are actually inferred from the literal values they initialize. As with the previous int and double, if you set a ture or false for them when you create them, you do not need to indicate them as a bool when you want to declare them. Type inference can help Swift's code be more concise and readable, and its type is actually known when a constant or variable is initialized with another value. Boolean values are particularly useful in conditional statements, such as the IF condition:

If turnipsaredelicious{

println ("Mmm, Tasty turnips!")

}else{

println ("Eww, turnips is horrible.")

}

Print out "eww,turnips is horrible"

More detailed information about conditional statements such as the IF condition statement is described in the "Swift Control Flow" subsection.

Type safety for Swift prevents non-boolean values from being used in place of Boolean values. The following example will report a compile-time error:

Let I =1

If I {

This example will not compile and report an error

}

However, the alternative for the following example will be passed:

Let I =1

If i==1{

This example will be compiled successfully by

The result of the I==1 comparison is a Boolean type, so the second example can be detected by type, and comparisons like I==1 will be discussed in detail in the section "Basic operational operations of Swift".

In conjunction with other swift type safety examples, this will help to avoid accidental errors and ensure that specific code is clearer.

Swift's Boolean

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.