0
0
Swiftprogramming~20 mins

Protocol declaration syntax in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Protocol Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple protocol conformance
What is the output of this Swift code when calling greet() on person?
Swift
protocol Greeter {
    func greet() -> String
}

struct Person: Greeter {
    func greet() -> String {
        return "Hello!"
    }
}

let person = Person()
print(person.greet())
ANo output
B"Hello!"
C"Hi!"
DError: Protocol method not implemented
Attempts:
2 left
💡 Hint
Check how the greet() method is implemented in Person.
Predict Output
intermediate
2:00remaining
Protocol with property requirement output
What will be printed by this Swift code?
Swift
protocol Identifiable {
    var id: String { get }
}

struct User: Identifiable {
    var id: String
}

let user = User(id: "abc123")
print(user.id)
Anil
BError: Missing property implementation
C"id"
D"abc123"
Attempts:
2 left
💡 Hint
Look at how id is defined and initialized in User.
🔧 Debug
advanced
2:00remaining
Identify the syntax error in protocol declaration
Which option contains the syntax error in this protocol declaration?
Swift
protocol Vehicle {
    var speed: Int
    func drive()
}
AThe property <code>speed</code> must specify { get } or { get set }
BThe function <code>drive()</code> must have a return type
CProtocols cannot have properties
DThe protocol keyword is misspelled
Attempts:
2 left
💡 Hint
Check how properties are declared in protocols.
🧠 Conceptual
advanced
2:00remaining
Protocol inheritance syntax
Which option correctly declares a protocol FlyingCar that inherits from protocols Car and Flyable?
Aprotocol FlyingCar: Car, Flyable {}
Bprotocol FlyingCar inherits Car, Flyable {}
Cprotocol FlyingCar <- Car, Flyable {}
Dprotocol FlyingCar extends Car & Flyable {}
Attempts:
2 left
💡 Hint
Look at how Swift declares protocol inheritance using colons and commas.
Predict Output
expert
3:00remaining
Output of protocol extension method call
What is the output of this Swift code?
Swift
protocol Speaker {
    func speak() -> String
}

extension Speaker {
    func speak() -> String {
        return "Hello from extension"
    }
}

struct Robot: Speaker {
    func speak() -> String {
        return "Hello from Robot"
    }
}

struct Alien: Speaker {}

let r = Robot()
let a = Alien()
print(r.speak())
print(a.speak())
A"Hello from Robot"\nCompilation error
BCompilation error: Alien does not implement speak()
C"Hello from Robot"\n"Hello from extension"
D"Hello from extension"\n"Hello from extension"
Attempts:
2 left
💡 Hint
Check how protocol extensions provide default implementations.