Last active
September 15, 2015 08:17
-
-
Save JadenGeller/f8ad2574590f956fee92 to your computer and use it in GitHub Desktop.
Aspect Oriented 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
struct Aspect<T,V> { | |
let backing: T -> V | |
init(_ function: T -> V) { | |
backing = function | |
} | |
var preceedingActions = Array<(T, V) -> ()>() | |
mutating func doAfter(action: (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 | |
println("The square of \(input) is \(output).") | |
} | |
var sum = 0 | |
for x in 0...5 { | |
sum += square.call(x) | |
} | |
println("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