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.

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for advice, but there is no argument with index(of: ) in here. What should it be?
Take a look again at my example, you will see it's the index of your currNr string.
index(of: ) only exists for objects that conform to Equatable developer.apple.com/documentation/swift/equatable
Oh i see, i declare the array with [Any], i change it into [String] . Its work thanks
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"}

Comments

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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.