0
0
Swiftprogramming~20 mins

Arithmetic operators and overflow in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Overflow 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 with overflow?
Consider the following Swift code using overflow addition. What will be printed?
Swift
var maxUInt8: UInt8 = 255
maxUInt8 = maxUInt8 &+ 1
print(maxUInt8)
A0
B256
C255
DRuntime error
Attempts:
2 left
💡 Hint
Think about what happens when an 8-bit unsigned integer goes beyond its max value.
Predict Output
intermediate
2:00remaining
What is the result of this subtraction with overflow?
What will this Swift code print when subtracting with overflow?
Swift
var minInt8: Int8 = -128
minInt8 = minInt8 &- 1
print(minInt8)
A127
B-129
C-128
DRuntime error
Attempts:
2 left
💡 Hint
Remember Int8 ranges from -128 to 127 and &- allows wrapping.
🔧 Debug
advanced
2:00remaining
Why does this Swift code cause a runtime error?
This code tries to add two Int values. Why does it crash?
Swift
let a: Int = Int.max
let b: Int = 1
let c = a + b
print(c)
ABecause Int.max is not a valid integer
BBecause Int addition does not allow overflow and crashes on overflow
CBecause b is not an Int
DBecause print cannot print large integers
Attempts:
2 left
💡 Hint
Check what happens when adding 1 to the maximum Int value without overflow operators.
🧠 Conceptual
advanced
2:00remaining
Which operator safely adds two UInt8 values allowing overflow?
Which Swift operator adds two UInt8 values and allows overflow without crashing?
A+
B-
C&+
D&-
Attempts:
2 left
💡 Hint
Look for the operator with an ampersand that allows overflow.
Predict Output
expert
3:00remaining
What is the output of this mixed overflow and normal addition code?
Analyze this Swift code and determine what it prints.
Swift
var x: UInt8 = 250
let y: UInt8 = 10
let z = x &+ y
let w = x + y
print(z)
print(w)
A
260
4
B
4
260
C
Runtime error
4
D
4
Runtime error
Attempts:
2 left
💡 Hint
Consider which addition allows overflow and which does not.