0
0
Swiftprogramming~5 mins

Protocol declaration syntax in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a protocol in Swift?
A protocol in Swift is like a blueprint that defines methods, properties, or other requirements that a class, struct, or enum can adopt and implement.
Click to reveal answer
beginner
How do you declare a protocol in Swift?
Use the keyword protocol followed by the protocol name and curly braces containing the requirements. For example:<br>
protocol MyProtocol {
    func doSomething()
}
Click to reveal answer
intermediate
Can protocols declare properties in Swift? If yes, how?
Yes, protocols can declare properties. They specify whether the property must be gettable or gettable and settable. For example:<br>
protocol Example {
    var name: String { get set }
    var id: Int { get }
}
Click to reveal answer
beginner
What does it mean when a protocol property is declared with { get } only?
It means the property must be readable (gettable) but does not have to be writable (settable).
Click to reveal answer
intermediate
How do you specify that a protocol inherits from other protocols?
List the protocols separated by commas after the protocol name. For example:<br>
protocol Combined: ProtocolA, ProtocolB {
    // requirements
}
Click to reveal answer
Which keyword is used to declare a protocol in Swift?
Aclass
Binterface
Cstruct
Dprotocol
How do you declare a read-only property requirement in a protocol?
Avar propertyName: Type { get }
Bvar propertyName: Type
Clet propertyName: Type
Dvar propertyName: Type { get set }
Can a struct adopt a protocol in Swift?
AYes, structs can adopt protocols.
BNo, only classes can adopt protocols.
COnly enums can adopt protocols.
DProtocols cannot be adopted by any type.
How do you declare a protocol that inherits from two other protocols named A and B?
Aprotocol NewProtocol inherits A, B
Bprotocol NewProtocol extends A, B
Cprotocol NewProtocol: A, B
Dprotocol NewProtocol implements A, B
Which of the following is NOT a valid protocol requirement?
Avar count: Int { get set }
Bprivate func helper()
Cinit(value: Int)
Dfunc doWork()
Explain how to declare a protocol in Swift and include property and method requirements.
Think about the blueprint idea and how you list requirements.
You got /3 concepts.
    Describe how protocol inheritance works in Swift and why it might be useful.
    Consider how you can build on existing blueprints.
    You got /3 concepts.