Created
February 14, 2017 13:38
-
-
Save anonymous/ff4440ac74c87d451502984d3125b095 to your computer and use it in GitHub Desktop.
Aspect Oriented Swift (Swift3 version of JadenGeller/Aspect.swift)
This file contains 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
#! /usr/bin/env swift | |
//Original code: https://gist.github.com/JadenGeller/f8ad2574590f956fee92 | |
struct Aspect<T,V> { | |
let backing: (T) -> V | |
init(_ function: @escaping (T) -> V) { | |
backing = function | |
} | |
var preceedingActions = Array<(T, V) -> ()>() | |
mutating func doAfter(action: @escaping (_ input: T, _ output: V) -> ()) { | |
preceedingActions.append(action) | |
} | |
func call(_ input: T) -> V { | |
let result = backing(input) | |
for action in preceedingActions { | |
action(input, result) | |
} | |
return result | |
} | |
} | |
// Example | |
var square = Aspect { (x: Int) -> Int in x * x } | |
square.doAfter { input, output in | |
print("The square of \(input) is \(output).") | |
} | |
var sum = 0 | |
for x in 0...5 { | |
sum += square.call(x) | |
} | |
print("The sum of square from 0 to 5 is \(sum).") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment