Swift 3: delete value in array with unknown index

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

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

If I clicked the grid, I placed it in a new array self.arrayNr.append(currNr).

But I want to check and delete, if currNralready exists in arrayNr, it will be deleted from arrayNr.

I am new and using Swift 3. I read some question regarding my question such as this and this but it does not work. I think Swift 2 is easier than Swift 3 when processing String. Any sugesstion or answer help me?

+4
source share
3 answers

index(of, , currNr . ( Equatable)

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)
+2

, , [String]. , .

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

, , , "1"

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

array = array.filter(){$0 != "1"}
+1

Long decision

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 decision

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"]
+1
source

Source: https://habr.com/ru/post/1681080/


All Articles