Last active
December 15, 2018 21:06
-
-
Save richimf/ab94aae479c862b993ab38268c5b6d1b to your computer and use it in GitHub Desktop.
Protocol dispatching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MARK: - Protocol definitions | |
protocol InputProtocol { | |
var a: Int { get } | |
var b: Int { get } | |
} | |
protocol Addition: InputProtocol {} | |
extension Addition { | |
func operation() -> Int{ | |
return a + b | |
} | |
} | |
protocol Subtraction: InputProtocol {} | |
extension Subtraction { | |
func operation() -> Int{ | |
return a - b | |
} | |
} | |
protocol Multiplication: InputProtocol {} | |
extension Multiplication { | |
func operation() -> Int{ | |
return a * b | |
} | |
} | |
// MARK: - Struct and typealias definitions | |
typealias Operations = Addition & Subtraction & Multiplication | |
struct Calculator: Operations { | |
var a: Int | |
var b: Int | |
//Default operation | |
func operation() -> Int{ | |
return 0 | |
} | |
} | |
// MARK: - Implementation | |
let calculation = Calculator(a: 5, b: 3) | |
let add: Addition = calculation | |
add.operation() // prints 8 | |
let sub: Subtraction = calculation | |
sub.operation() // prints 2 | |
let mult: Multiplication = calculation | |
mult.operation() // prints 15 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment