Swift snippet #10โ€Šโ€”โ€Šremove(d)

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 ๐Ÿ˜Š