Protocols, Delegation & SwiftUI2.0

Mixing Protocol Programming with Declarative Coding

Mark Lucking
The Startup

--

A simple app that synchronises the colour of the text/square using a delegate invoked with a tap gesture

There are dozens of programming paradigms with many languages supporting multiple ones. Swift is no exception and supports objected oriented coding with classes and inheritance, declarative coding with SwiftUI with states and protocol oriented programming with protocols and generic types. Indeed Swift’s support for the paradigm is one of the strongest for a leading language in the industry. Support that Dave Abrahams one of the principle architects behind Swift design and implementation describes as one of its primary goals.

All of which — is an odd state of affairs given you don’t find many tutorials or even papers on the subject — no sadly it seems almost everyone is still looking at Object-Oriented Coding even with Swift. So let’s break mould before the end of the year and take a short journey to explored how you can use protocols & delegation in your Swift code.

Implementing a method within a protocol

The brief, lets build a traffic light using protocols, to code. Unsurprisingly to start using POP we begin with a protocol, a protocol that looks like this.

protocol Actionable {
func changeable()
}

--

--

Mark Lucking
The Startup

Coding for 35+ years, enjoying using and learning Swift/iOS development. Writer @ Better Programming, @The StartUp, @Mac O’Clock, Level Up Coding & More