0
0
Swiftprogramming~5 mins

Protocol requirements (methods and properties) 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 and properties a type must have. It tells what to do, but not how to do it.
Click to reveal answer
beginner
Can protocols require both methods and properties?
Yes, protocols can require methods (functions) and properties (variables) that conforming types must implement.
Click to reveal answer
intermediate
What does it mean when a protocol property is declared with { get set }?
It means the property must be readable and writable by the conforming type.
Click to reveal answer
beginner
How do you declare a method requirement in a Swift protocol?
You write the method signature without a body inside the protocol. For example: <br>func start()
Click to reveal answer
intermediate
Can protocol requirements specify if a property is a variable or constant?
No, protocols only specify if a property is gettable or settable. The conforming type decides if it uses var or let.
Click to reveal answer
What must a type do when it conforms to a protocol with property requirements?
AIgnore property requirements
BOnly implement methods, properties are optional
CImplement all required properties with correct get/set access
DImplement properties but methods are optional
How do you declare a read-only property requirement in a protocol?
Avar name: String { set }
Bvar name: String { get }
Clet name: String
Dfunc name() -> String
Which of these is a valid method requirement in a Swift protocol?
Afunc run()
Bfunc run() {}
Cfunc run() -> Void {}
Dfunc run() -> Void { print("Run") }
If a protocol requires a property with { get set }, can a conforming type implement it as a constant (let)?
AOnly if the property is static
BYes, constants are allowed
COnly if the property is private
DNo, it must be a variable (var) to allow setting
What happens if a type does not implement all protocol requirements?
ACompilation error
BThe program runs but with warnings
CThe missing requirements are ignored
DThe protocol is automatically changed
Explain what protocol requirements are in Swift and how they apply to methods and properties.
Think about what a protocol asks a type to provide.
You got /4 concepts.
    Describe the difference between { get } and { get set } in protocol property requirements.
    Focus on property access levels.
    You got /4 concepts.