1

I have an Array that is declared as:

var stringsArray: Array<String!> = []

I want to add items to it using code along these lines:

stringsArray.append("String 1")

However, I would like to use an if statement to detect whether or not what is about to be appended already exists in stringsArray and if it does, I would like the code to append not to be ran.

I am using Swift.

4
  • 1
    Maybe a Set would be a better choice?... Commented Jul 2, 2015 at 9:44
  • @Alladinian: I would turn your comment into an answer - that is the solution Commented Jul 2, 2015 at 9:46
  • A Set does not have defined ordering but I do need to be manipulate the order of the contents. Am I able to do this using a Set? Commented Jul 2, 2015 at 9:48
  • @DanielBramhall Then I guess you could use an NSMutableOrderedSet Commented Jul 2, 2015 at 9:55

1 Answer 1

3

You can simply use this:

var elements = [1,2,3,4,5]
if contains(elements, 5) {
    print("Array contains 3")
}

For Swift 2.2 and later, there is a member contains():

var elements = [1, 2, 3, 4, 5]
if elements.contains(3) {
    print("Array contains 3")
}

Resource: How to check if an element is in an array.

Sign up to request clarification or add additional context in comments.

5 Comments

If you copy code verbatim from another answer then you should add a link to the source: stackoverflow.com/a/25391725/1187415.
This doesn't work as it says that Swift cannot find an overload for contains that accepts an argument list of type (Array<String!>, String)
True that, forgot about that, editing in a minute.
Any ideas regarding my issue? Thanks!
Check the link above, that should solve your problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.