0
0
Swiftprogramming~20 mins

Why let and var distinction matters in Swift - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Let and Var Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of code using let and var

What is the output of this Swift code?

Swift
let x = 10
var y = 20
y = y + 5
print(x, y)
A15 20
B10 25
C10 20
DCompilation error
Attempts:
2 left
💡 Hint

Remember that let creates a constant and var creates a variable.

Predict Output
intermediate
2:00remaining
What error occurs when modifying a let constant?

What error does this Swift code produce?

Swift
let a = 5
a = 10
print(a)
ACompilation error: Cannot assign to value: 'a' is a 'let' constant
BRuntime error
COutput: 10
DNo error, output: 5
Attempts:
2 left
💡 Hint

Think about whether constants can be changed after assignment.

🧠 Conceptual
advanced
2:00remaining
Why use let instead of var?

Which reason best explains why using let is preferred when possible?

ABecause <code>let</code> variables can be changed later if needed
BBecause <code>var</code> variables use less memory
CBecause <code>let</code> makes the code safer by preventing accidental changes
DBecause <code>var</code> variables are slower to access
Attempts:
2 left
💡 Hint

Think about safety and bugs in your code.

Predict Output
advanced
2:00remaining
Value after modifying a var inside a function

What is the output of this Swift code?

Swift
var count = 1
func increment() {
    count += 1
}
increment()
print(count)
ARuntime error
B1
CCompilation error
D2
Attempts:
2 left
💡 Hint

Consider how var variables can be changed inside functions.

🔧 Debug
expert
2:00remaining
Why does this code fail to compile?

Why does this Swift code fail to compile?

Swift
func updateValue() {
    let number = 10
    number += 5
    print(number)
}
updateValue()
ABecause you cannot change a constant declared with let
BBecause the function is missing a return type
CBecause print cannot be used inside functions
DBecause the variable number is not initialized
Attempts:
2 left
💡 Hint

Look at how number is declared and then changed.