Swift snippet #10 — remove(d)

Ritesh Gupta
Swift Snippets 🚀
1 min readFeb 16, 2017

Thursday, 16th February, 2017

You can find its Gist here!

  • remove — it takes a closure to remove an element that matches the provided condition & returns the removed element. Its a mutating func which means it modifies the host array
var list = [1, 2, 3, 4]
let removedItem = list.remove { $0 == 2 } // mutating
removedItem -> 2
list -> [1, 3, 4]
  • removed — it takes a closure to remove an element that matches the provided condition & returns a new array. It doesn’t affect the host array.
let list = [1, 2, 3, 4]
let newList = list.removed { $0 == 2 } // non-mutating
list -> [1, 2, 3, 4]
newList -> [1, 3, 4]

These 2 functions removes some of the boilerplate code to simply remove an element which shouldn’t be that hard 🚀

PS — In my next snippet, I’ll share 2 more remove(d) methods which removes all the elements matching a given condition!

If you are wondering about the inception of Swift-Snippets or want to checkout more such snippets, you can find them here 😊

--

--