Introduction To Protocol Oriented Programming

We are going to solve the implementation of this by making them both Computed Properties, and declaring a private backing storage for them.Now that we’re done specifying the functionality in the protocols, we refactor our classes to conform to the appropriate protocols and we hide everything that is not supposed to be available from outside the classes:class Car: Moveable, Lockable { private var _position: CGPoint private var _isLocked = true var isLocked: Bool { return self._isLocked } var position: CGPoint { return self._position } init(position: CGPoint) { self._position = position } public func move(x: CGFloat, y: CGFloat) { self._position.x += x self._position.y += y } public func lock() { self._isLocked = true } public func unlock() { self._isLocked = false }}class Carrier: Moveable, Loadable { private var _position: CGPoint private var loadedStuff = [Moveable]() var position: CGPoint { return self._position } init(position: CGPoint) { self._position = position } public func move(x: CGFloat, y: CGFloat) { self._position.x += x self._position.y += y self.loadedStuff.forEach { (thing) in thing.move(x: x, y: y) } } public func load(_ thing: Moveable) { self.loadedStuff.append(thing) } public func unload(_ thing: Moveable) { self.loadedStuff = self.loadedStuff.filter({ $0 !== thing }) } // This method no longer works,// because a Moveable object has no unlock() method.//// public func itsWeirdThatACarrierCanDoThis() {// self.loadedStuff.forEach { (thing) in// thing.unlock()// }// }}Notice that when we let the Carrier deal with objects that implement the Moveable protocol, it lost access to all methods and properties that does not concern moving something around..What makes this approach even better is that it brings extensibility to our code..Our carrier no longer has a clue of exactly what it’s moving around, so as long as we let new classes implement the Moveable protocol, we can haul cars, boats, furniture… Pretty much anything that makes sense to move, all without changing a single line of code in our Carrier class.You may also remember from previous articles that structs and Bools are Value Types..Our Computed Properties are able to return the backing storage variable directly because of the fact that a Value Type will be copied every time it’s passed off somewhere, meaning that we will never have any alias problems with our positions.Are There Any More Advantages To Protocols?I’m glad you asked.Protocols are not all about information hiding..Our second example shows how protocols (together with generics) can make your programs more flexible, as well as reduce the amount of code you need to write..Take a look at this:class Arithmetic { static func add(a: Int, b: Int) -> Int { return a + b }}This is a very contrived example, but I think it will get the point across.What you see is a method performing a simple addition and returning the result, and it’s not doing anything wrong per se.However, when we look closer we realize that we’re going to need to write a lot of these to cover all the different types of numbers that you may want to add together..Floats will need a method, Doubles will need one, etc..We want to implement a single function that accepts several different types and provides a correct answer, but we also want to specify some constraints on what those types can be (it wouldn’t, for example, make sense to try to add two Strings in this situation)..Let’s try to refine this method definition in our next example:class Arithmetic { static func add<Type: Numeric>(a: Type, b: Type) -> Type { return a + b }}Beautiful!.We now have a function that’s using a protocol as a generic constraint..This allows us to handle any number of types with the same method, the condition being that the type must implement the Numeric protocol and thereby allowing us to perform arithmetic operations on it.Hopefully, this article brought some new insights and maybe sparked a few ideas about how to use Protocol Oriented Programming in your own projects..Feel free to comment if you have questions, and follow to get notifications about future articles.To learn more about iOS Development, check out my previous articles:Using Swift Extensions To Clean Up Our CodeSwift extensions were created to add functionality to entities where the source code is unavailable, but can we use…medium.comUnderstanding ARC’s Effect On Your App’s PerformanceWhat is ARC and how does it affect the performance of our code?medium.comThis story is published in The Startup, Medium’s largest entrepreneurship publication followed by +401,714 people.Subscribe to receive our top stories here.. More details

Leave a Reply