Skip to content

Instantly share code, notes, and snippets.

@opsb
Last active February 17, 2022 15:34
Show Gist options
  • Select an option

  • Save opsb/f2cad0241fcb4a4b957feeacc10bc0f2 to your computer and use it in GitHub Desktop.

Select an option

Save opsb/f2cad0241fcb4a4b957feeacc10bc0f2 to your computer and use it in GitHub Desktop.

Revisions

  1. opsb revised this gist May 28, 2020. 1 changed file with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions Usage.swift
    Original file line number Diff line number Diff line change
    @@ -6,3 +6,10 @@ print(array, updatedArray)
    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]
  2. opsb revised this gist May 28, 2020. 1 changed file with 8 additions and 0 deletions.
    8 changes: 8 additions & 0 deletions Usage.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    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]
  3. opsb created this gist May 28, 2020.
    32 changes: 32 additions & 0 deletions NonMutatingArray.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    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
    }
    }