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 😊

It’s an initiative to share snippets that leverages the great power of Swift 🤘

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
Ritesh Gupta

Ritesh Gupta

iOS Developer

More from Medium

Async/await for existing apps

Swift | Making an API Call and Fetching JSON

Stacks In SwiftUI: IOS Development -Part-2

H-Stack, V-Stack & Z-Stack in swiftUI

macOS App,1. Set Document Type