Last active
February 17, 2022 15:34
-
-
Save opsb/f2cad0241fcb4a4b957feeacc10bc0f2 to your computer and use it in GitHub Desktop.
Swift extension to add non mutating methods to Array
This file contains hidden or 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 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 | |
} | |
} |
This file contains hidden or 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
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