Celebrating 200 Daily Coding Tips 🎉 all tutorials will be free to all this week!
Sometimes it’s useful to create a protocol to define a required feature.
Every Button
requires an action
closure, and the temptation can be to pass these in when the Button
is created. I want to make it easier to enforce the existence of a closure as a property of the view, so I created Actionable
. In an extension I created a default implementation, so that every Button has the ability to add an action before I’ve decided what the action will actually be.
Extensions can only return computed properties, so that’s why the action is created without using the =
symbol. It’s essentially a closure that returns a closure.
Underneath I have created ButtonWithDefaultAction
, which can magically contain a Button
without defining an action
!
There are other ways to use this protocol too.
When adding conformance to the Actionable
protocol, Xcode will suggest that you add the missing stubs that are required. This will give you an action
property that is declared without being initialized, which will automatically require the closure to be passed into the view. As you can see in ContentView
, ButtonWithRequiredAction
can be given a trailing closure that provides the action.
ButtonWithSpecificAction
defines its own action, and so it does not require a closure to be passed in. The actions defined by these buttons overwrite the default print("Actionable")
action provided by the extension of Actionable
. One use for the Actionable extension could be to create an assertionFailure
or even a fatalError
, serving as a reminder to eventually implement a custom action for a given Button
.
If you find yourself adding similar properties to numerous views, it makes sense to define a protocol that defines that requirement.