Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array of strings, including "like" condition

If my main array is ["Hello","Bye","Halo"], and I'm searching for "lo", it will filter the array only to ["Hello", "Halo"].

This is what I've tried:

 let matchingTerms = filter(catalogNames) {         $0.rangeOfString(self.txtField.text!, options: .CaseInsensitiveSearch) !=  nil     } 

It throws

Type of expression is ambiguous without more context 

Any suggestions?

like image 886
Roi Mulia Avatar asked Dec 29 '15 13:12

Roi Mulia


People also ask

How do you filter an array based on string?

To filter strings of an Array based on length in JavaScript, call Array. filter() method on this String Array, and pass a function as argument that returns true for the specific condition on string length or false otherwise.

How do you add multiple conditions to a filter?

If you want to put multiple conditions in filter , you can use && and || operator.


1 Answers

Use contains instead:

let arr = ["Hello","Bye","Halo"] let filtered = arr.filter { $0.contains("lo") } print(filtered) 

Output

["Hello", "Halo"]

Thanks to @user3441734 for pointing out that functionality is of course only available when you import Foundation

like image 114
luk2302 Avatar answered Sep 21 '22 13:09

luk2302