Swift: finding array objects
I want to search in an array of objects in swift but I didn't know how :(
I tried
filteredArrayUsingPredicate
but still doesn't work, it gives me an error message
- Update -
error message
swift:42:9: 'Array<search_options>' does not have a member named 'filteredArrayUsingPredicate'
- Update -
class search_options {
let id:String
let option:String
init(){}
init(id:String ,option:String){
self.id = id
self.option = option
}
}
I only want to search in a parameter variable
And when I tried to use
func searchBarSearchButtonClicked( searchBar: UISearchBar!)
{
let filteredArray = filter(search_options_array) { $0 == "test" }
println(searchBar.text)
}
I received this message
swift:40:58: 'search_options' is not a subtype of 'String'
source to share
Finally after a long search I did't! I was looking for a way to do dynamic search, for example if the String array contains
"hello","lo","yes"
and I want to get all lines containing like "lo" I want to get "hello" and "lo"
so the best way I found was regex search
so I am doing a For Loop by throwing all parameters into Array and comparing each object variable with the pattern and storing it in a new array on objects
for var i = 0; i < search_options_array.count; i++ {
let myRegex = "searched_text"
if let match = search_options_array[i].option.rangeOfString(myRegex, options: .RegularExpressionSearch){
filtered_options_array.append(search_options(id:search_options_array[i].id,option:search_options_array[i].option) )
}
}
The best part here is you can take full advantage of regex and have a copy of your old array, so if you need it.
Thanks everyone for the help.
source to share
Since it filter
takes as a predicate a function that maps each element of a given value Array
to a value Bool
(to determine which value to filter out), in your case it might be like this:
let a = [
search_options(id: "a", option: "X"),
search_options(id: "b", option: "Y"),
search_options(id: "c", option: "X")
]
let b = filter(a) { (e: search_options) in e.option == "X" }
// ==> [search_options(id: "a", option: "X"), search_options(id: "c", option: "X")]
source to share
Correct answer
func searchBarSearchButtonClicked( searchBar: UISearchBar!)
{
let filteredArray = filter(search_options_array) { $0.option == "test" }
println(searchBar.text)
}
or
func searchBarSearchButtonClicked( searchBar: UISearchBar!)
{
let filteredArray = filter(search_options_array) { $0.id == "test" }
println(searchBar.text)
}
You should get the property of the object you are searching with
source to share