How to remove an element from an array in Swift

后端 未结 18 2160
灰色年华
灰色年华 2020-11-28 18:38

How can I unset/remove an element from an array in Apple\'s new language Swift?

Here\'s some code:

let animals = [\"cats\", \"dogs\", \"chimps\", \"m         


        
18条回答
  •  情歌与酒
    2020-11-28 18:58

    Regarding @Suragch's Alternative to "Remove element of unknown index":

    There is a more powerful version of "indexOf(element)" that will match on a predicate instead of the object itself. It goes by the same name but it called by myObjects.indexOf{$0.property = valueToMatch}. It returns the index of the first matching item found in myObjects array.

    If the element is an object/struct, you may want to remove that element based on a value of one of its properties. Eg, you have a Car class having car.color property, and you want to remove the "red" car from your carsArray.

    if let validIndex = (carsArray.indexOf{$0.color == UIColor.redColor()}) {
      carsArray.removeAtIndex(validIndex)
    }
    

    Foreseeably, you could rework this to remove "all" red cars by embedding the above if statement within a repeat/while loop, and attaching an else block to set a flag to "break" out of the loop.

提交回复
热议问题