Empty protocols can be useful as we've seen previously, but protocols are meant to provide requirements.
Protocols can require different aspects of objects:
- Properties, their type, and accessibility
- Methods
- Initializers
protocol DemoProtocol {
var aRequiredProperty: String { get set }
var aReadonlyProperty: Double { get }
static var aStaticProperty: Int { get set }
init(requiredProperty: String)
func doSomething() -> Bool
}
The previous DemoProtocol protocol exposes all of the requirements a conforming class should provide:
- aRequiredProperty should be String that can be read and written.
- aReadonlyProperty should be Double, but should only be at least readable. Conforming classes can implement it as let or as a computed property.
- aStaticProperty is a static Int member; conforming classes expose them as vars.
- Conforming classes should provide an initializer that takes String as an argument.
- Conforming classes should expose a non mutating function doSomething() that returns Bool.
You can implement this protocol with a class or a structure or even an enumeration.