Kodeco Forums

Swift Tutorial Part 3: Flow Control

In Part 3 of this Swift tutorial mini-series, you’ll learn how to use comparison operators, if statements, loops and switch statements to make intelligent decisions in your code.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/965-swift-tutorial-part-3-flow-control

Hi Matt,
Thanks a lot for beautiful description and tutorial.
I have a doubt regarding fallthrough keyword

I tried following piece of code
let x = 10
switch x
{
case _ where x%2==0:
print(“Two’s multiple”)
fallthrough
case _ where x%3==0:
print(“Three’s multiple”)
fallthrough
case _ where x%5==0:
print(“Five’s multiple”)
default:
print(“Odd”)
}

I ran this with playground and expected the output to be
“Two’s multiple\n”
“Five’s multiple\n”

However I received
“Two’s multiple\n”
“Three’s multiple\n”
“Five’s multiple\n”

It would be great if you could please help me understand? Does fallthrough means compulsory execution of next case? I assumed it was just to continue case matching

Hi @anoopnyati!

I can see your confusion! But yes, what you say about compulsory execution is correct. fallthrough means that it will always execute the next case as well.

Hey @mattjgalloway,
Thanks for the reply :slight_smile:

That’s interesting, so fallthrough means compulsory execution of next statement!

So is it possible to achieve the behaviour in Swift that I wanted to, in the above example i.e. fall through next case but execute only if the case value matches?

I recommend chaining ‘if’ statements rather than using a switch in your case.

@mattjgalloway

Thanks for these tutorials ! I bought the ‘2D apple games by tutorials’ book and was finding it hard to follow.

I did this mini series and now realise learning a few things about swift first is probably really beneficial !

it took me 16 hours over 5 days to get through all the content here, I could do all the challenges ( but they werent easy ! )

thanks again for this great content.

This tutorial is more than six months old so questions are no longer supported at the moment for it. We will update it as soon as possible. Thank you! :]