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.
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 arrayif 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/noresult:
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)
Try like this.
Swift 3.0
import UIKitlet 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"]