Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Conditional Statements

Swift Conditional Statements

A conditional statement decides which block of code to execute based on whether one or more conditions are true.

Swift provides if, switch, guard, and the ternary operator; their common prerequisite is that the condition must be a Bool.


if statement

An if statement consists of a Boolean condition and a code block, which executes only when the condition is true.

Example

func checkIf

(

_ varA

:

Int

)

{

   

if

varA

<

20

{

print

(

"varA is less than 20"

)

   

}

    print

(

"The value of varA is (varA)"

)

}

checkIf

(

10

)

The execution result of the above program is:



varA 小于 20

varA 变量的值为 10

Note that the braces after if can't be omitted, even if the block contains only one line.


if-else and else-if chains

An if can be followed by an else, whose branch runs when the condition is false.

Example

func checkIfElse

(

_ varA

:

Int

)

{

   

if

varA

<

20

{

print

(

"varA is less than 20"

)

   

}

else

{

        print

(

"varA is greater than or equal to 20"

)

   

}

}

checkIfElse

(

100

)

The execution result of the above program is:



varA 大于或等于 20

To test multiple conditions, chain them with else if; once a branch matches, none of the later branches run.

Example

func checkChain

(

_ score

:

Int

)

{

   

if

score

==

20

{

        print

(

"The value of score is 20"

)

   

}

else

if

score

==

50

{

        print

(

"The value of score is 50"

)

   

}

else

if

score

=

80

{

        print

(

"score is greater than or equal to 80"

)

   

}

else

{

        print

(

"No condition matched"

)

   

}

}

checkChain

(

85

)

The execution result of the above program is:



score 大于等于 80


Nested if

You can nest another if inside the block of an if or else if, forming nested conditions.

Example

func checkNested

(

_ n1

:

Int, _ n2

:

Int

)

{

   

if

n1

==

100

{

        print

(

"The first condition is true"

)

       

if

n2

==

200

{

            print

(

"The second condition is also true"

)

       

}

   

}

}

checkNested

(

100

,

200

)

The execution result of the above program is:



第一个条件为 true

第二个条件也是 true

Too many nesting levels hurt readability; in that case switch to guard for early exit or extract the condition into a separate function.


Conditions must be Bool

Swift requires a genuine Bool in the condition position; integers, strings, and optionals can't be used directly as conditions.

Example

func checkBool

(

_ count

:

Int, flag

:

Bool

)

{

   

if

count

0

{

         

// Use a comparison to obtain a Bool

        print

(

"count is positive"

)

   

}

   

if

flag

{

             

// flag is itself a Bool

        print

(

"flag is true"

)

   

}

}

checkBool

(

3

, flag

:

true

)

The execution result of the above program is:



count 是正数

flag 为 true

Using an integer directly as a condition fails to compile.

Example

let count

=

3

if

count

{

    print

(

"count is nonzero"

)

}

The compiler reports the error:



error: type 'Int' cannot be used as a boolean; test for '!= 0' instead

Note:Swift has no implicit conversion like C's "0, empty string, or null pointer is false," nor does it have a not keyword; for negation use !. To use an optional as a condition, unwrap it first; see article 29 《Swift Optional Types》。


Ternary Operator

condition ? value1 : value2 is the expression form of if-else, suited to choosing between two values.

Example

func voteText

(

_ age

:

Int

)

String

{

   

return

age

=

18

?

"Can vote"

:

"Can't vote"

}

print

(

voteText

(

20

)

)

print

(

voteText

(

15

)

)

The execution result of the above program is:



可以投票

不能投票

Deeply nested ternary expressions are hard to read; beyond two levels, switch back to if-else.


switch statement

A switch compares a value against several cases one by one, executing the matching branch.

Unlike C, a Swift case ends automatically after execution—no break needed, and no fall-through to the next case.

Interval matching

A case can contain a range directly, useful for bucketing continuous values like scores or ages.

Example

func gradeText

(

_ grade

:

Int

)

String

{

   

switch

grade

{

   

case

90

...

100

:

       

return

"Excellent"

   

case

80

..

<

90

:

       

return

"Good"

   

case

60

..

<

80

:

       

return

"Pass"

   

default

:

       

return

"Fail"

   

}

}

print

(

gradeText

(

85

)

)

The execution result of the above program is:



良好

Tuple matching

Combine multiple values into a tuple, then use a patterned case to match several dimensions at once; the underscore _ means "don't care" for that position.

Example

func axisText

(

_ coord

:

(

Int, Int

)

)

String

{

   

switch

coord

{

   

case

(

0

,

0

)

:

       

return

"Origin"

   

case

(

_,

0

)

:

       

return

"On the x-axis"

   

case

(

0

, _

)

:

       

return

"On the y-axis"

   

default

:

       

return

"Elsewhere"

   

}

}

print

(

axisText

(

(

0

,

5

)

)

)

The execution result of the above program is:



在 y 轴上

Value binding and where

With case let (x, y) you can bind matched values to local constants, then add extra conditions with where.

Example

func diagonalText

(

_ point

:

(

Int, Int

)

)

String

{

   

switch

point

{

   

case

let

(

x, y

)

where x

==

y

:

       

return

"((x), (y)) is on the main diagonal"

   

case

let

(

x, y

)

where x

==

y

:

       

return

"((x), (y)) is on the anti-diagonal"

   

case

let

(

x, y

)

:

       

return

"((x), (y)) is an ordinary point"

   

}

}

print

(

diagonalText

(

(

3

,

3

)

)

)

The execution result of the above program is:



(3, -3) 在反对角线上

Multiple-value matching and default

A case can list several comma-separated values, and matching any one of them suffices.

Example

func indexText

(

_ index

:

Int

)

String

{

   

switch

index

{

   

case

100

:

       

return

"The value of index is 100"

   

case

10

,

15

:

       

return

"The value of index is 10 or 15"

   

case

5

:

       

return

"The value of index is 5"

   

default

:

       

return

"Default case"

   

}

}

print

(

indexText

(

10

)

)

The execution result of the above program is:



index 的值为 10 或 15

Note:It can be omitted only when the switch already covers every possibility default. For Int such types with infinitely many values you must write default; for Bool or enums with all cases listed, it can be omitted.

Example

// Bool has only true and false, so two cases are exhaustive and no default is needed

func boolText

(

_ flag

:

Bool

)

String

{

   

switch

flag

{

   

case

true

:

       

return

"True"

   

case

false

:

       

return

"False"

   

}

}

print

(

boolText

(

true

)

, boolText

(

false

)

)

The execution result of the above program is:



真 假

@unknown default

When a switch's value comes from ananother module's enum, that enum may gain new cases in the future, so use @unknown default as a fallback.

Example

// Suppose direction's type comes from another module and the enum isn't frozen

switch

direction

{

case

.

north

:

    print

(

"North"

)

case

.

south

:

    print

(

"South"

)

@unknown

default

:

    print

(

"Unknown direction"

)

}

The code above can't run on its own because direction's type must be supplied by an external module.

@unknown default works like this: when a newer enum version adds cases, the compiler warns you to handle them instead of failing the build.

Note:If the enum is defined in the same file, the compiler already knows all its cases; in that case writing @unknown default won't silence the "switch must be exhaustive" warning—you still must list all cases, so within the same module just use default .


fallthrough

By default a Swift case ends after execution; if you truly want to continue into the next case, write fallthrough explicitly.

Example

func fallthroughDemo

(

_ idx

:

Int

)

{

   

switch

idx

{

   

case

100

:

        print

(

"The value of index is 100"

)

   

case

10

,

15

:

        print

(

"The value of index is 10 or 15"

)

        fallthrough

   

case

5

:

        print

(

"The value of index is 5"

)

   

default

:

        print

(

"Default case"

)

   

}

}

fallthroughDemo

(

10

)

The execution result of the above program is:



index 的值为 10 或 15

index 的值为 5

Note:fallthrough It performs no further condition checks and enters the next case's block directly. It can only fall into ordinary cases; if the next case binds variables, the compiler reports 'fallthrough' from a case which doesn't bind variable。


Early exit with guard

guard is used to leave the current scope early when a condition isn't met; its else branch must exit (return, break, continue, or throw).

By filtering out the failing cases up front, the main logic loses a level of indentation and reads more smoothly.

Example

func checkAge

(

_ age

:

Int

)

String

{

    guard age

=

18

else

{

       

return

"Underage, not allowed in"

   

}

   

return

"Adult, welcome in"

}

print

(

checkAge

(

20

)

)

print

(

checkAge

(

15

)

)

The execution result of the above program is:



已成年,欢迎进入

未成年,不能进入

guard let is its most common form: unwrap an optional, exit on failure, and on success the unwrapped constant stays available in subsequent code.

Example

func greet

(

_ name

:

String

?

)

String

{

    guard let name

=

name,

!

name.

isEmpty

else

{

       

return

"Hello, guest"

   

}

   

// By this point name is already a non-empty String

   

return

"Hello, (name)"

}

print

(

greet

(

"Runoob"

)

)

print

(

greet

(

nil

)

)

The execution result of the above program is:



你好,Runoob

你好,游客


Common questions

The following questions come up most often when writing conditional statements.

Problem Description
if 1 { } Why the error The condition must be Bool, change it to if 1 != 0 { }
switch 's default Can it be omitted Yes when exhaustive;Int this kind must use
case Write after it break ? No need; Swift doesn't fall through by default
guard and if How to choose Use it when you need early exit and less indentation guard; for pure branch selection, use if
guard Can variables be declared inside it Yes, but variables declared there guard remain available afterwards; this is the main difference from if let its counterpart