Skip to content

Instantly share code, notes, and snippets.

@Happytreat
Last active May 13, 2020 04:21
Show Gist options
  • Save Happytreat/5278f00e4db728b7fdb60519f1de5010 to your computer and use it in GitHub Desktop.
Save Happytreat/5278f00e4db728b7fdb60519f1de5010 to your computer and use it in GitHub Desktop.
refactored protocol example
/**
* Adapted Example from Protocol Oriented Programming - Advanced Swift Programming - raywenderlich.com
* https://www.youtube.com/watch?v=ekYdBcl3dzs
*/
// Base class for inheritance
class Shape {
var size: CGSize
func draw(on context: CGContext) { fatalError("override \(#function)") }
func area() -> CGFloat { return size.width * size.height }
}
// With refactored protocols
protocol Drawable {
func draw(on context: CGContext)
}
protocol Geometry {
var size: CGSize { get }
func area() -> CGFloat
}
// default implementation of area
extension Geometry {
func area() -> CGFloat { return size.width * size.height }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment