Check if array contains part of a string in Swift?

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.


Try like this.

Swift 3.0

import UIKit

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

var filterdItemsArray = [String]()


func filterContentForSearchText(searchText: String) {
    filterdItemsArray = itemsArray.filter { item in
        return item.lowercased().contains(searchText.lowercased())
    }
}

filterContentForSearchText(searchText: "Go")
print(filterdItemsArray)

Output

["Google", "Goodbye", "Go"]

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)