Image for post
Image for post

Protocol-Oriented Programming in Swift

Andrea Prearo
Feb 2, 2016 · 8 min read

Object-Oriented Programming 101: Classical Inheritance

Image for post
Image for post
Initial application architecture
Image for post
Image for post
Adding new functionality

The issues with Classical Inheritance

… the problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.

Joe Armstrong

A better approach to modeling: Composition over Inheritance

“Program to an interface, not an implementation.”

“Favor ‘object composition’ over ‘class inheritance’.”

Design Patterns — GoF

Image for post
Image for post
A composable architecture

The Swift way: Protocols and Protocol Extensions

protocol Runnable {
var groundSpeed: Double { get }
func run() -> String
}
extension Runnable {
func run() -> String {
return "Running at \(groundSpeed) mph"
}
}
protocol Swimmable {
var waterSpeed: Double { get }
func swim() -> String
}
extension Swimmable {
func swim() -> String {
return "Swimming at \(waterSpeed) mph"
}
}

protocol Flyable {
var airSpeed: Double { get }
func fly() -> String
}
extension Flyable {
func fly() -> String {
return "Flying at \(airSpeed) mph"
}
}
class Penguin : Bird, Runnable, Swimmable {
var groundSpeed = 2.0
var waterSpeed = 25.0
}

Conclusion

iOS App Development

Stories and technical tips about building apps for iOS…

Andrea Prearo

Written by

Experienced iOS Engineer and Software Craftsman with extensive expertise in building reusable libraries and components to scale development teams and products.

iOS App Development

Stories and technical tips about building apps for iOS, Apple Watch, and iPad/iPhone

Andrea Prearo

Written by

Experienced iOS Engineer and Software Craftsman with extensive expertise in building reusable libraries and components to scale development teams and products.

iOS App Development

Stories and technical tips about building apps for iOS, Apple Watch, and iPad/iPhone

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store