Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array contains part of a string in Swift?

I have an array containing a number of strings. I have used contains() (see below) to check if a certain string exists in the array however I would like to check if part of a string is in the array?

itemsArray = ["Google, Goodbye, Go, Hello"]  searchToSearch = "go"  if contains(itemsArray, stringToSearch) {     NSLog("Term Exists") } else {     NSLog("Can't find term") } 

The above code simply checks if a value is present within the array in its entirety however I would like to find "Google, Google and Go"

like image 492
Daniel Bramhall Avatar asked Jun 14 '15 10:06

Daniel Bramhall


People also ask

How do you check a string contains a substring in Swift?

To check if a string contains another string, we can use the built-in contains() method in Swift. The contains() method takes the string as an argument and returns true if a substring is found in the string; otherwise it returns false .

How do you check if a variable is in an array Swift?

To check if an element is in an array in Swift, use the Array. contains() function.


2 Answers

Try like this.

let itemsArray = ["Google", "Goodbye", "Go", "Hello"] let searchToSearch = "go"  let filteredStrings = itemsArray.filter({(item: String) -> Bool in       var stringMatch = item.lowercaseString.rangeOfString(searchToSearch.lowercaseString)      return stringMatch != nil ? true : false }) 

filteredStrings will contain the list of strings having matched sub strings.

In Swift Array struct provides filter method, which will filter a provided array based on filtering text criteria.

like image 100
Amit89 Avatar answered Sep 20 '22 07:09

Amit89


First of all, you have defined an array with a single string. What you probably want is

let itemsArray = ["Google", "Goodbye", "Go", "Hello"] 

Then you can use contains(array, predicate) and rangeOfString() – optionally with .CaseInsensitiveSearch – to check each string in the array if it contains the search string:

let itemExists = contains(itemsArray) {     $0.rangeOfString(searchToSearch, options: .CaseInsensitiveSearch) !=  nil }  println(itemExists) // true  

Or, if you want an array with the matching items instead of a yes/no result:

let matchingTerms = filter(itemsArray) {     $0.rangeOfString(searchToSearch, options: .CaseInsensitiveSearch) !=  nil }  println(matchingTerms) // [Google, Goodbye, Go] 

Update for Swift 3:

let itemExists = itemsArray.contains(where: {     $0.range(of: searchToSearch, options: .caseInsensitive) != nil }) print(itemExists)  let matchingTerms = itemsArray.filter({     $0.range(of: searchToSearch, options: .caseInsensitive) != nil }) print(matchingTerms) 
like image 34
Martin R Avatar answered Sep 20 '22 07:09

Martin R