Skip to content

Instantly share code, notes, and snippets.

@opsb
Last active February 17, 2022 15:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save opsb/f2cad0241fcb4a4b957feeacc10bc0f2 to your computer and use it in GitHub Desktop.
Save opsb/f2cad0241fcb4a4b957feeacc10bc0f2 to your computer and use it in GitHub Desktop.
Swift extension to add non mutating methods to Array
extension Array {
func inserted(_ element: Element, at index: Int) -> Array<Element> {
return updated({$0.insert(element, at: index)})
}
func appended(_ element: Element) -> Array<Element> {
return updated({$0.append(element)})
}
func appended(contentsOf elements: Array<Element>) -> Array<Element> {
return updated({$0.append(contentsOf: elements)})
}
// added for convenience
func prepended(_ element: Element) -> Array<Element> {
inserted(element, at: 0)
}
func removed(_ element: Element, at index: Int) -> Array<Element> {
return updated({$0.remove(at: index)})
}
func lastRemoved(_ element: Element) -> Array<Element> {
return updated({$0.removeLast()})
}
func updated(_ cb: (inout Array<Element>) -> Void) -> Array<Element> {
var working = self
cb(&working)
return working
}
}
let array = [1,2,3]
let updatedArray = array.prepended(0).appended(4).appended(contentsOf: [5,6,7])
print(array, updatedArray)
// [1, 2, 3] [0, 1, 2, 3, 4, 5, 6, 7]
let updatedByCallback = array.updated { $0[0] = 3 }
print(array, updatedByCallback)
// [1, 2, 3] [3, 2, 3]
let updatedByBatchOfMutations = array.updated {
$0.insert(10, at: 0)
$0.append(20)
}
print(array, updatedByBatchOfMutations)
// [1, 2, 3] [10, 1, 2, 3, 20]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment