Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Last active August 29, 2015 14:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/8f2753a9db31d857054e to your computer and use it in GitHub Desktop.
Save JadenGeller/8f2753a9db31d857054e to your computer and use it in GitHub Desktop.
Swift Array Copy By Inserting/Removing
// Extension to Array that adds insertion and removal operations that make copies
// instead of mutating the array
extension Array {
func appended(newValue: T) -> Array {
var copy = self
copy.append(newValue)
return copy
}
func inserted(newValue: T, atIndex index: Int) -> Array {
var copy = self
copy.insert(newValue, atIndex: index)
return copy
}
func removedRange(subRange: Range<Int>) -> Array {
var copy = self
copy.removeRange(subRange)
return copy
}
func removedAtIndex(index: Int) -> Array {
let (_, arr) = takeAtIndex(index)
return arr
}
func removedLast() -> Array {
let (_, arr) = takeLast()
return arr
}
func takeAtIndex(index: Int) -> (T, Array) {
var copy = self
let result = copy.removeAtIndex(index)
return (result, copy)
}
func takeLast() -> (T, Array) {
var copy = self
let result = copy.removeLast()
return (result, copy)
}
mutating func prepend(newValue: T) {
insert(newValue, atIndex: 0)
}
func prepended(newValue: T) -> Array {
var copy = self
copy.prepend(newValue)
return copy
}
}
// Example
var arr = [1, 2, 3, 4, 5]
let removedSecond = arr.removedAtIndex(1)
let insertedFirst = arr.inserted(8, atIndex: 0)
let tookLast = arr.takeLast()
println(arr) // [1, 2, 3, 4, 5]
println(removedSecond) // [1, 3, 4, 5]
println(insertedFirst) // [8, 1, 2, 3, 4, 5]
println(tookLast) // (5, [1, 2, 3, 4])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment