Daniel Bramhall Daniel Bramhall - 1 month ago 10
Swift Question

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"

Answer

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.