Created
March 23, 2015 23:16
-
-
Save JadenGeller/df09f33eb23bb3463039 to your computer and use it in GitHub Desktop.
Swift Shields
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
// Creates a new function from an inout function | |
// that does not modify the passed in arugment | |
// but returns a modified argument and result | |
func shield<T,U>(action: inout T -> U) -> T -> (T, U) { | |
return { arg in | |
var copy = arg | |
let result = action(©) | |
return (copy, result) | |
} | |
} | |
// Example | |
var arr = [1,2,3] | |
let last = shield(removeLast)(arr) | |
let removeFirst = { (inout x : Array<Int>) in removeAtIndex(&x, 0) } | |
let first = shield(removeFirst)(arr) | |
println(arr) // -> [1, 2, 3] | |
println(last) // -> ([1, 2], 3) | |
println(first) // -> ([2, 3], 1) | |
// Note that the value of arr never changed! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment