Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created March 23, 2015 23:16
Show Gist options
  • Save JadenGeller/df09f33eb23bb3463039 to your computer and use it in GitHub Desktop.
Save JadenGeller/df09f33eb23bb3463039 to your computer and use it in GitHub Desktop.
Swift Shields
// 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(&copy)
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