0
0
Swiftprogramming~5 mins

For-in loop with ranges in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a for-in loop in Swift?
A for-in loop in Swift repeats a block of code for each item in a sequence, like numbers or arrays.
Click to reveal answer
beginner
How do you create a range from 1 to 5 in Swift?
You write 1...5 to create a range including numbers 1 through 5.
Click to reveal answer
intermediate
What is the difference between 1...5 and 1..<5 in Swift?
1...5 includes 1, 2, 3, 4, 5. 1..<5 includes 1, 2, 3, 4 but not 5.
Click to reveal answer
beginner
Write a simple Swift for-in loop that prints numbers 1 to 3.
for number in 1...3 { print(number) } This prints 1, then 2, then 3 each on a new line.
Click to reveal answer
intermediate
Can you use a for-in loop with ranges to count backwards in Swift?
Yes! Use stride(from:to:by:) or stride(from:through:by:) to count backwards with a for-in loop.
Click to reveal answer
What does the range 1...5 include in Swift?
ANumbers 1, 2, 3, 4
BNumbers 1, 2, 3, 4, 5
CNumbers 2, 3, 4, 5
DNumbers 0 to 5
Which Swift syntax counts from 1 up to but not including 5?
A1..<5
B1...5
C1..5
D1-5
How do you write a for-in loop to print numbers 1 to 3 in Swift?
Afor i in 3...1 { print(i) }
Bfor i in 1..<3 { print(i) }
Cfor i in 1...3 { print(i) }
Dfor i = 1 to 3 { print(i) }
Which method helps count backwards in a for-in loop with ranges?
AcountBack()
Brange(from:to:by:)
CreverseRange()
Dstride(from:to:by:)
What will this code print? for i in 1..<4 { print(i) }
A1 2 3
B1 2 3 4
C2 3 4
D1 2 3 4 5
Explain how to use a for-in loop with a range in Swift to repeat an action multiple times.
Think about how to write a loop that counts from 1 to 5.
You got /3 concepts.
    Describe the difference between closed and half-open ranges in Swift and how they affect for-in loops.
    Focus on whether the last number is included or not.
    You got /4 concepts.