0
0
Swiftprogramming~20 mins

Var for variables (mutable) in Swift - Practice Problems & Coding Challenges

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

Consider this Swift code snippet. What will it print?

Swift
var count = 5
count = 10
print(count)
A10
B5
CCompilation error
DRuntime error
Attempts:
2 left
💡 Hint

Remember, var allows the value to change.

Predict Output
intermediate
2:00remaining
What happens if you try to change a let constant?

What error will this Swift code produce?

Swift
let name = "Alice"
name = "Bob"
print(name)
ARuntime error
BCompile-time error: Cannot assign to value: 'name' is a 'let' constant
CPrints Alice
DPrints Bob
Attempts:
2 left
💡 Hint

let means the value cannot be changed after assignment.

🔧 Debug
advanced
2:30remaining
Why does this code cause an error?

Examine this Swift code. Why does it fail to compile?

Swift
var number = 10
number = "ten"
print(number)
APrints 10
BRuntime error: Invalid type conversion
CPrints "ten"
DType mismatch error: Cannot assign String to Int variable
Attempts:
2 left
💡 Hint

Swift variables have fixed types once declared.

🧠 Conceptual
advanced
2:00remaining
What is the difference between var and let in Swift?

Choose the best explanation of the difference between var and let in Swift.

A<code>var</code> and <code>let</code> are interchangeable and have no difference.
B<code>var</code> declares a constant; <code>let</code> declares a mutable variable.
C<code>var</code> declares a mutable variable; <code>let</code> declares an immutable constant.
D<code>var</code> is used only for integers; <code>let</code> is used only for strings.
Attempts:
2 left
💡 Hint

Think about whether the value can change after assignment.

Predict Output
expert
3:00remaining
What is the output of this Swift code with var and scope?

What will this Swift code print?

Swift
var x = 5
if true {
    var x = 10
    print(x)
}
print(x)
A
10
5
B
5
10
C
10
10
D
5
5
Attempts:
2 left
💡 Hint

Remember that variables declared inside a block have their own scope.