Dinker Malhotra
Dinker Malhotra

Reputation: 37

Compare a NSArray with NSString in swift?

I have a array with some words and I want to check whether these words exist in my string or not. Here is the sample code

var array: NSArray = ["one", "two", "three", "four"]

var Str: NSString = "one example of my string"

Now one exist in the string, but I am not able to compare them. How to get that one compared?

Upvotes: 0

Views: 549

Answers (4)

Milos
Milos

Reputation: 2758

If simple Bool result is what you need:

array.contains{ string.containsString(String($0)) } // true

However, I would suggest working with Swift's Array and String value types instead and then extending String as follows:

public extension String {

    public func containsAny(strings: [String]) -> Bool {
        return strings.contains{ containsString($0) }
    }
}

let strings = ["one", "two", "three", "four"]
let string = "one example of my string"

string.containsAny(strings) // true

Upvotes: 0

ronatory
ronatory

Reputation: 7324

To use a method if you have different arrays of strings to check you can do it like that:

var array: NSArray = ["one", "two", "three", "four"]

var str: NSString = "one example of my string"

func checkIfStringOfArrayExists(arrayOfString: NSArray, inString string: NSString) -> Bool {
    for element in array where str.containsString(element as! String) {
        return true
    }
    return false
}

checkIfStringOfArrayExists(array, inString: str) // true

Upvotes: 0

Emptyless
Emptyless

Reputation: 3050

You can use the NSString.containsString(string) method:

let Str : NSString = "This is one string"
let array : [NSString] = ["one", "two", "three", "four"]

for word in array {
    print("is \(word) mentioned in string? : \(Str.containsString(word as String))" )
}

with output:

  • is one mentioned in string? : true
  • is two mentioned in string? : false
  • is three mentioned in string? : false
  • is four mentioned in string? : false

Upvotes: 0

Sandeep
Sandeep

Reputation: 21144

Do it like this,

var array: NSArray = ["one", "two", "three", "four"]

var Str: NSString = "one example of my string"

let filteredString = Str.componentsSeparatedByString(" ").filter { a in
    return array.containsObject(a)
}
print(filteredString)

Upvotes: 1

Related Questions