Challenge - 5 Problems
Swift Operator Overloading Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of custom operator overloading
What is the output of this Swift code that overloads the + operator for a custom struct?
Swift
struct Point { var x: Int var y: Int static func + (lhs: Point, rhs: Point) -> Point { Point(x: lhs.x + rhs.x, y: lhs.y + rhs.y) } } let p1 = Point(x: 3, y: 4) let p2 = Point(x: 5, y: 7) let p3 = p1 + p2 print("(\(p3.x), \(p3.y))")
Attempts:
2 left
💡 Hint
Think about how the + operator is defined for Point and what it returns.
✗ Incorrect
The + operator is overloaded to add the x and y values of two Point instances. So (3+5, 4+7) = (8, 11).
🧠 Conceptual
intermediate1:30remaining
Purpose of operator overloading
Why do programmers use operator overloading in Swift?
Attempts:
2 left
💡 Hint
Think about how operators work with built-in types and why you might want the same for your own types.
✗ Incorrect
Operator overloading lets you define how operators like +, -, * behave with your own types, making code easier to read and write.
🔧 Debug
advanced2:00remaining
Identify the error in operator overloading
What error does this Swift code produce when trying to overload the * operator for a struct?
Swift
struct Vector { var value: Int static func * (lhs: Vector, rhs: Vector) -> Int { lhs.value * rhs.value } } let v1 = Vector(value: 2) let v2 = Vector(value: 3) let result = v1 * v2 print(result)
Attempts:
2 left
💡 Hint
Check the return type of the operator function and how it is used.
✗ Incorrect
The operator * is defined to return Int, which is allowed. The code prints 6 correctly.
❓ Predict Output
advanced2:00remaining
Output of prefix operator overloading
What is the output of this Swift code that overloads the prefix - operator for a struct?
Swift
struct Temperature { var celsius: Double static prefix func - (value: Temperature) -> Temperature { Temperature(celsius: -value.celsius) } } let temp = Temperature(celsius: 25.0) let negTemp = -temp print(negTemp.celsius)
Attempts:
2 left
💡 Hint
Consider what the prefix - operator does to the celsius value.
✗ Incorrect
The prefix - operator returns a new Temperature with the negative of the original celsius value, so -25.0 is printed.
📝 Syntax
expert3:00remaining
Correct syntax for custom infix operator
Which option correctly declares and implements a custom infix operator ** for exponentiation on Int in Swift?
Attempts:
2 left
💡 Hint
Remember that operator functions must be static and the operator must be declared before use.
✗ Incorrect
Option B correctly declares the infix operator and defines a static function with proper types and return value.