Challenge - 5 Problems
Swift Extension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of extension method call
What is the output of this Swift code using an extension?
Swift
extension Int { func squared() -> Int { return self * self } } let number = 4 print(number.squared())
Attempts:
2 left
💡 Hint
Think about what multiplying a number by itself means.
✗ Incorrect
The extension adds a method 'squared' to Int that returns the number multiplied by itself. 4 * 4 equals 16.
❓ Predict Output
intermediate2:00remaining
Extension adding computed property
What will be printed by this Swift code that uses an extension with a computed property?
Swift
extension String { var isLong: Bool { return self.count > 5 } } let word = "Swift" print(word.isLong)
Attempts:
2 left
💡 Hint
Count the letters in the word "Swift".
✗ Incorrect
The word "Swift" has 5 letters, which is not greater than 5, so isLong returns false.
🔧 Debug
advanced2:00remaining
Why does this extension cause a compile error?
This Swift extension code causes a compile error. What is the reason?
Swift
extension Int { func multiply(by: Int) -> Int { return self * by } func multiply(by: Int) -> Int { return self * by * 2 } }
Attempts:
2 left
💡 Hint
Think about method overloading rules in Swift.
✗ Incorrect
Swift does not allow two methods with the same name and parameter types in the same scope, even in extensions.
📝 Syntax
advanced2:00remaining
Identify the correct extension syntax
Which option shows the correct syntax to add a method named 'greet' to the String type using an extension?
Attempts:
2 left
💡 Hint
Remember the full function declaration syntax in Swift.
✗ Incorrect
Option A correctly declares a method with 'func', parentheses, and a body. Others miss parentheses or return types or have syntax errors.
🚀 Application
expert3:00remaining
Using extension to add a protocol conformance
Given this protocol and struct, which extension correctly adds conformance to the protocol by implementing the required method?
Swift
protocol Describable { func describe() -> String } struct Car { let brand: String let year: Int }
Attempts:
2 left
💡 Hint
To conform to a protocol, implement all required methods with correct signatures in an extension that declares conformance.
✗ Incorrect
Option B correctly declares Car conforms to Describable and implements describe() returning String. Option B lacks conformance declaration. Option B extends the protocol, not Car. Option B has wrong method signature (missing return type).