Mastering Swift
上QQ阅读APP看书,第一时间看更新

The Boolean type

Boolean values are often referred to as logical values because they can be either true or false. Swift has a built-in Boolean type called Bool that accepts one of two built-in Boolean constants. These constants are true and false.

Boolean constants and variables can be defined like this:

let swiftIsCool = true
let swiftIsHard = false

var itIsWarm = false
var itIsRaining = true

Boolean values are especially useful when working with conditional statements, such as if and while. For example, what do you think this code would do:

let isSwiftCool = true
let isItRaining = false
if (isSwiftCool) {
    println("YEA, I cannot wait to learn it")
}

if (isItRaining) {
    println("Get a rain coat")
}

If you answered that this code would print out YEA, I cannot wait to learn it, then you would be correct. Since isSwiftCool is set to true, the YEA, I cannot wait to learn it message is printed out, but isItRaining is false; therefore, the Get a rain coat is not.

You can also assign a Boolean value from a comparison operator like this:

var x = 2, y = 1
var z = x > y

In the preceding code, z is a Boolean variable containing a Boolean true value.