Um momento
0x40Lesson 5 of 7

Repeat work with loops and collections

Use loops and arrays to process many values.

15 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Iterate through collections and accumulate results.

Swift arrays hold ordered values. Use for value in values to iterate cleanly, or use ranges like 0..<count when you need indexes. Build running totals with mutable variables and keep loop bodies simple.

main.swift
1let scores = [8, 7, 10]
2var total = 0
3for score in scores {
4    total += score
5}
6print(total)
Output
25

..< is a half-open range that includes the start and excludes the end. This is ideal for zero-based indexing because 0..<array.count stays in bounds.

Key takeaways

  • Iterate through collections and accumulate results.

  • Swift favors clear intent and safe defaults.

  • Compiler feedback is part of the learning loop.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Swift

These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning C.

Exercise 1

Sum N numbers

+25 XP

Read a count, then read that many integers (one per line), and print their sum.

  • Three numbers
  • Negative number
main.swift
Loading editor…

Swift lessons are authored for Swift 6.4; exercises run on Swift 6.0.1 via Wandbox, a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: