4

I want to implement a multiple click in my Shinobi DataGrid. I have a grid which have array

( ["1", "32", and more] )

If I click the grid I put it into new Array self.arrayNr.append(currNr).

But I want to check and remove if currNr is already exist in arrayNr it is will be remove from the arrayNr.

I'm new and using Swift 3. I read some question regarding with my question like this and this but it's not working. I think the Swift 2 is simpler than Swift 3 in handling for String. Any sugesstion or answer will help for me?

rmaddy
  • 307,833
  • 40
  • 508
  • 550
MrX
  • 913
  • 1
  • 13
  • 40

3 Answers3

2

You can use index(of to check if the currNrexists in your array. (The class must conform to the Equatable protocol)

var arrayNr = ["1", "32", "100"]
let currNr = "32"
// Check to remove the existing element
if let index = arrayNr.index(of: currNr) {
    arrayNr.remove(at: index)
}
arrayNr.append(currNr)
iwasrobbed
  • 45,890
  • 20
  • 149
  • 193
Lawliet
  • 3,350
  • 1
  • 16
  • 26
  • thanks for advice, but there is no argument with `index(of: )` in here. What should it be? – MrX Jul 10 '17 at 02:01
  • Take a look again at my example, you will see it's the index of your *currNr* string. – Lawliet Jul 10 '17 at 02:03
  • 1
    `index(of: )` only exists for objects that conform to `Equatable` https://developer.apple.com/documentation/swift/equatable – iwasrobbed Jul 10 '17 at 03:07
  • Oh i see, i declare the array with [Any], i change it into [String] . Its work thanks – MrX Jul 10 '17 at 03:29
1

Say you have an array of string, namely type [String]. Now you want to remove a string if it exists. So you simply need to filter the array by this one line of code

stringArray= stringArray.filter(){$0 != "theValueThatYouDontWant"}

For example, you have array like this and you want to remove "1"

let array = ["1", "32"] 

Simply call

array = array.filter(){$0 != "1"}
Fangming
  • 23,035
  • 4
  • 95
  • 87
1

Long Solution

sampleArray iterates over itself and removes the value you are looking for if it exists before exiting the loop.

var sampleArray = ["Hello", "World", "1", "Again", "5"]
let valueToCheck = "World"

for (index, value) in sampleArray.enumerated() {
    if value == valueToCheck && sampleArray.contains(valueToCheck) {
        sampleArray.remove(at: index)
        break
    }
}

print(sampleArray) // Returns ["Hello", "1", "Again", "5"]

Short Solution

sampleArray returns an array of all values that are not equal to the value you are checking.

var sampleArray = ["Hello", "World", "1", "Again", "5"]
let valueToCheck = "World"

sampleArray = sampleArray.filter { $0 != valueToCheck }

print(sampleArray) // Returns ["Hello", "1", "Again", "5"]
ArtSabintsev
  • 5,152
  • 10
  • 39
  • 71