Last active
August 29, 2015 14:17
-
-
Save JadenGeller/8f2753a9db31d857054e to your computer and use it in GitHub Desktop.
Swift Array Copy By Inserting/Removing
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
// 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