2

I want to remove element of custom type value from an array.

I want to pass a variant instance to function to remove it from array, I don't want to use removeAtIndex().

var favoriteVariants: [Variant]

func removeVariant(variant: Variant)
{
}
Bannings
  • 10,376
  • 7
  • 44
  • 54

1 Answers1

0

If Variant is Equatable and you only want to remove the first one that matches:

if let idx = favoriteVariants.indexOf(variant) {
    favoriteVariants.removeAtIndex(idx)
}

If it isn’t Equatable and you have some other matching criteria to find just one to remove:

let idx = favoriteVariants.indexOf {
   // match $0 to variant
}

if let idx = idx {
    favoriteVariants.removeAtIndex(idx)
}

(these are assuming Swift 2.0 – if 1.2, it’s find(favoriteVariants, variant) instead of indexOf, and there isn’t a version that takes a closure, though it’s not too hard to write one)

If there are multiple ones you want to remove in one go:

favoriteVariants = favoriteVariants.filter {
    // criteria to _keep_ any given favorite
}

All of these could be wrapped in extensions if what you want to do is general enough to justify it.

Community
  • 1
  • 1
Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118
  • User need not use " i don't want to use removeAtIndex()." But your using – Arun Jul 02 '15 at 10:14
  • I took that to mean, “I don’t have the index” (so gave a way to find it) rather than an arbitrary constraint to avoid using a method for no reason. – Airspeed Velocity Jul 02 '15 at 10:16
  • Thanks Airspeed Velocity, i'm using swift 1.2 now and i got this when used find. Connot invoke 'find' with an argument list of type '([Varaint], Variant)' – Mohammad Shawamreh Jul 02 '15 at 10:26