Skip to content

Instantly share code, notes, and snippets.

@atierian
Created June 19, 2021 17:40
Show Gist options
  • Select an option

  • Save atierian/eb727deec1795f687ec23ce47f517a03 to your computer and use it in GitHub Desktop.

Select an option

Save atierian/eb727deec1795f687ec23ce47f517a03 to your computer and use it in GitHub Desktop.
import Foundation
import XCTest
extension MutableCollection {
/// Iterates through a mutable collection and mutates values based on the closure argument
/// - Parameter closure: Takes and element and mutates it
mutating func mutatingForEach(_ closure: (inout Element) -> Void) {
indices.forEach {
closure(&self[$0])
}
}
}
class MutatingForEachTests: XCTestCase {
var sut = [1, 2, 3, 4, 5, 6, 7, 8]
func testMutation() {
let copy = sut
sut.mutatingForEach { $0 *= 2 }
sut.enumerated().forEach {
XCTAssertNotEqual($0.element, copy[$0.offset])
XCTAssertEqual($0.element / 2, copy[$0.offset])
}
}
}
MutatingForEachTests.defaultTestSuite.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment