Skip to content

Instantly share code, notes, and snippets.

@richimf
Last active December 15, 2018 21:06
Show Gist options
  • Save richimf/ab94aae479c862b993ab38268c5b6d1b to your computer and use it in GitHub Desktop.
Save richimf/ab94aae479c862b993ab38268c5b6d1b to your computer and use it in GitHub Desktop.
Protocol dispatching
// 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