-1

I want to remove a specific string value from an array that contains duplicates.

let array = ["orange", "apple", "orange", "peach"]

Is there a way to remove the SECOND value of orange from the array?

My example:

var array = [String]()
var fruit: String!

@IBAction func likeButtonAction(_ sender: UIButton) {

  if array.contains(fruit) {
   array.remove(at: array.firstIndex(of: fruit)!)
  } else {
  array.append(fruit)
  }

UserDefaults.standard.set(array, forKey: "fruit")

}
Dian
  • 115
  • 3
  • 12
  • Simply change `firstIndex` to `lastIndex`. But how do you end up with more than one instance of a fruit in the array if you never allow more than one instance in the array? – HangarRash Apr 24 '23 at 01:09
  • @HangarRash I am trying to remove the fruit depends on the position in the table view. I can have rows with the same fruit and same value. Basically, I need to be able to add/remove string from array depending on user input. Hope that make more sense. Thanks. – Dian Apr 24 '23 at 04:31

1 Answers1

0

UPDATE:

If you are using a button to add/remove values from the list of fruits and you are utilizing a set. When you click the add button, first check if the fruit is already in the set, if it is, then don't add it.

When you click the remove button, remove it from the set.





You can iterate through the array storing unique values in a Set.
For each value in the array, check if the Set does not contain the current item. If it doesn't, then add it to the Set and to an output array. Repeat for each item to get an array of unique values.

i.e.

func unique<S : Sequence, T : Hashable>(inputArray: S) -> [T] where S.Iterator.Element == T {
    var output = [T]()
    var uniqueValues = Set<T>()
    for fruit in inputArray {
        if !uniqueValues.contains(fruit) {
            output.append(fruit)
            uniqueValues.insert(fruit)
        }
    }
    return output
}

let vals = ["orange", "grape", "strawberry", "strawberry", "apple", "orange", "raspberry"]
let uniqueVals = unique(vals) // ["orange", "grape", "strawberry", "apple", "raspberry"]
Keegan Fisher
  • 133
  • 1
  • 8
  • I am storing the array in UserDefaults.standard.set and accesses it in another View Controller. I am adding(append) and removing values with a button. My code works fine but removes only the first value of the array when I have duplicates values. – Dian Apr 23 '23 at 23:31
  • OK well this answer was to the first edit of your question, which asked how to remove duplicates from an array. I can post an update to answer your new question. – Keegan Fisher Apr 24 '23 at 01:00
  • 1
    @KeeganFisher The OP isn't using a Set. The OP's comment to your answer mentions the use of `UserDefaults.standard.set`. That's not the collection Set, that's the `set` method to store a value. The update should be rolled back. – HangarRash Apr 24 '23 at 03:24