Challenge - 5 Problems
Protocol Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate2:00remaining
Understanding Protocol Extensions
What will be printed when the following Swift code runs?
iOS Swift
protocol Greetable {
func greet() -> String
}
extension Greetable {
func greet() -> String {
return "Hello from protocol extension"
}
}
struct Person: Greetable {}
let p = Person()
print(p.greet())Attempts:
2 left
💡 Hint
Protocol extensions provide default implementations.
✗ Incorrect
Since Person does not implement greet(), the default implementation from the protocol extension is used.
❓ ui_behavior
intermediate2:00remaining
Protocol and UIViewController Behavior
Given a protocol with a default method to setup UI, which option correctly applies the protocol to a UIViewController subclass and calls the setup method?
iOS Swift
protocol UISetup {
func setupUI()
}
extension UISetup {
func setupUI() {
print("Default UI setup")
}
}
class MyViewController: UIViewController, UISetup {
override func viewDidLoad() {
super.viewDidLoad()
// Call setupUI here
}
}Attempts:
2 left
💡 Hint
Call the protocol method directly on self.
✗ Incorrect
The protocol method setupUI() is available on self because MyViewController conforms to UISetup. Calling setupUI() inside viewDidLoad works.
❓ lifecycle
advanced2:00remaining
Protocol-oriented Initialization
What error occurs when trying to compile this Swift code?
iOS Swift
protocol Identifiable {
var id: String { get }
init(id: String)
}
struct User: Identifiable {
let id: String
init(id: String) {
self.id = id
}
}
let user = User(id: "123")Attempts:
2 left
💡 Hint
Structs do not inherit protocol initializers automatically.
✗ Incorrect
User must implement the required init(id:) initializer explicitly to conform to Identifiable.
advanced
2:00remaining
Protocol and Navigation Controller
Which option correctly uses a protocol to define a navigation action and implements it in a UIViewController subclass?
iOS Swift
protocol Navigatable {
func navigateToDetail()
}
class ListViewController: UIViewController, Navigatable {
func navigateToDetail() {
let detailVC = UIViewController()
// Navigate to detailVC
}
}Attempts:
2 left
💡 Hint
Use navigationController to push new view controller.
✗ Incorrect
To navigate in a navigation stack, pushViewController is used on navigationController.
📝 Syntax
expert2:00remaining
Protocol Composition and Method Resolution
What is the output of this Swift code?
iOS Swift
protocol A {
func foo() -> String
}
protocol B {
func foo() -> String
}
extension A {
func foo() -> String { "From A" }
}
extension B {
func foo() -> String { "From B" }
}
struct C: A, B {}
let c = C()
print(c.foo())Attempts:
2 left
💡 Hint
Multiple protocol extensions provide the same method.
✗ Incorrect
The compiler cannot decide which foo() to use because both A and B provide default implementations, causing ambiguity.