2

I have an NSMutableArray that contains String values. I have a String variable and I want to check if it is contained in the array or not.

I tried using .contains() with String but it say:

Cannot convert value of type String to expected argument type...

var mutableArray = NSMutableArray()  // ["abc", "123"]
var string = "abc"

mutableArray.contains("abc") {       // above error in this line

}
3
  • 1
    Please show your code! And why are you not using a native Swift array? Commented Jun 11, 2016 at 10:59
  • Because I need to utilise the way it indexes the array and that I can manipulate it on the go. Edited my question Commented Jun 11, 2016 at 11:00
  • 1
    why dont you take a String array like var mutableArray = [String] and than just check as it is Commented Jun 11, 2016 at 11:04

2 Answers 2

2

Multiple ways to check element existence in NSMutableArray. i.e

if mutableArray.contains("abc")  
    print("found")  
else  
    print("not found")  

or

if contains(mutableArray, "abc")   
    print("found")  

or

if mutableArray.indexOfObject("abc") != NSNotFound
  print("found")  

If we want to check existence of element according of version of swift

Swift1

if let index = find(mutableArray, "abc")  
    print(index)

Swift 2

if let index = mutableArray.indexOf("abc")  
    print(index)
Sign up to request clarification or add additional context in comments.

Comments

1

I do still not understand why you cannot use a native Swift array, but okay.

Two possible solutions are to either use

let contains = mutableArray.contains { $0 as? String == "abc" }

or

let contains = mutableArray.containsObject("abc")

or

let contains = mutableArray.indexOfObject("abc") != NSNotFound

If you would use a native array you could simply do

var array = ["123", "abc"]
let contains = array.contains("abc")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.