Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active September 15, 2015 08:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/f8ad2574590f956fee92 to your computer and use it in GitHub Desktop.
Save JadenGeller/f8ad2574590f956fee92 to your computer and use it in GitHub Desktop.
Aspect Oriented Swift
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