Swift Control flow Quiz

Test your understanding of Swift Control flow by taking this Quiz

Swift Quiz #07  - Swift Control flow

5 mins read

1. What value does the function calculate() return?

  func calculate() -> Int {
var result = 0
for i in 1...5 {
if i % 2 == 0 {
result += i
} else {
result -= i
}
}
return result
}

2. Which of the following control flow statements in Swift can be used to exit the current iteration of a loop?

3. What is the output?

 func printNames() {
let names = ["John", "Amy", "Emily", "Michael"]
for name in names {
if name == "Amy" {
continue
}
print(name)
if name == "Emily" {
break
}
}
}

4. What is the primary difference between the `if` and `guard` statements in Swift?

5. What is the output?

 func calc() {
defer {
print("Step 3")
}
print("Step 1")
defer {
print("Step 4")
}
print("Step 2")
}

6. What is the output?

 func calc() -> Int {
var x = 10
repeat {
x += 5
} while x < 30
return x
}

7. What is the output when executed on iOS 16?

 func checkOS() {
let condition = false
if #available(iOS 14, *) {
print("Running on iOS 14 or later")
} else {
print("Running on earlier iOS version")
}
}

8. What is the output?

 func printChars() -> String {
var result = ""
for i in 1...3 {
switch i {
case 1, 3:
result += "A"
case 2:
result += "B"
default:
result += "C"
}
}
return result
}

9. What is the output?

func example() {
var x = 10
defer {
x += 5
}
if x > 5 {
print(x)
return
}
print(x - 5)
}