Grant Emerson

Be Thou Removed

Be Thou Removed — SwiftMoji Entry #15

One convenient instance method on Collections is the higher-order removeAll(where:) function. It operates on the calling Collection in-place, in constant time without the need to copy a return value. The where parameter is a user-provided closure that accepts an Element as input and returns a Bool determining which Elements are to be removed. The code example below compares two approaches for removing the even numbers from an [Int]. The first utilizes the filter(_:) method by negating a call to isEven and returning the result in the filter’s closure. Additionally, this solution requires the filtered array to be copied back into the original variable. The second approach uses the removeAll(where:) method in-place on the [Int] by passing the isEven closure in as an argument. The second approach is preferred due to its efficiency and increased readability.

var 🔢 = Array(1...100)
let isEven: (Int) -> Bool = { $0 % 2 == 0 }

// No 🚫
🔢 = 🔢.filter { !isEven($0) }

// Yes ✅
🔢.removeAll(where: isEven)
Tagged with: