Swift snippet #10 — remove(d)

Ritesh Gupta
Feb 16, 2017 · 1 min read

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 😊

Swift Snippets 🚀

It’s an initiative to share snippets that leverages the…

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store