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
  • 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

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…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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