NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

Summary: Conditions and loops

Paul Hudson    @twostraws   

Updated for Xcode 14.2

We’ve covered a lot about conditions and loops in the previous chapters, so let’s recap:

  • We use if statements to check a condition is true. You can pass in any condition you want, but ultimately it must boil down to a Boolean.
  • If you want, you can add an else block, and/or multiple else if blocks to check other conditions. Swift executes these in order.
  • You can combine conditions using ||, which means that the whole condition is true if either subcondition is true, or &&, which means the whole condition is true if both subconditions are true.
  • If you’re repeating the same kinds of check a lot, you can use a switch statement instead. These must always be exhaustive, which might mean adding a default case.
  • If one of your switch cases uses fallthrough, it means Swift will execute the following case afterwards. This is not used commonly.
  • The ternary conditional operator lets us check WTF: What, True, False. Although it’s a little hard to read at first, you’ll see this used a lot in SwiftUI.
  • for loops let us loop over arrays, sets, dictionaries, and ranges. You can assign items to a loop variable and use it inside the loop, or you can use underscore, _, to ignore the loop variable.
  • while loops let us craft custom loops that will continue running until a condition becomes false.
  • We can skip some or all loop items using continue or break respectively.

That’s another huge chunk of new material, but with conditions and loops you now know enough to build some really useful software – give it a try!

Hacking with Swift is sponsored by Essential Developer

SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.5/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.