Skip to content

Instantly share code, notes, and snippets.

Created February 14, 2017 13:38
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 anonymous/ff4440ac74c87d451502984d3125b095 to your computer and use it in GitHub Desktop.
Save anonymous/ff4440ac74c87d451502984d3125b095 to your computer and use it in GitHub Desktop.
Aspect Oriented Swift (Swift3 version of JadenGeller/Aspect.swift)
#! /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