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