Swift's branching features are in some cases more restrictive than the equivalents in other languages, and in other cases are considerably more powerful.
The if
, else
, and if else
statements work as they do in most C-based languages:
let x = getxFromSomewhere() if x == 0 { print("x is zero") } else if x < 0 { print("x is negative") } else { print("x is positive") }
The syntax is slightly different in that the condition to be tested does not need to be put in brackets. However, an important point to note is that the test must return a Bool
type value of true
or false
. Attempting to test an object for nil
as follows will raise a compiler error:
if possibleNil { // ... }
The error is shown in the following screenshot:
One final thing before we leave if
: the following will not compile:
if a = b { //... }
The assignment operator =
does not return a Bool
, and so using that instead of the intended ==
won't make it past the compiler. That...