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"
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 .
To check if an element is in an array in Swift, use the Array. contains() function.
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 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With