我想在swift中搜索对象数组 但我不知道如何:(
我试过
filteredArrayUsingPredicate
但仍然没有工作,它给我一个错误信息
- 更新 -
错误消息是
swift:42:9: 'Array<search_options>' does not have a member named 'filteredArrayUsingPredicate'
- 更新 -
class search_options {
let id:String
let option:String
init(){}
init(id:String ,option:String){
self.id = id
self.option = option
}
}
我只想搜索选项变量
当我尝试使用
时func searchBarSearchButtonClicked( searchBar: UISearchBar!)
{
let filteredArray = filter(search_options_array) { $0 == "test" }
println(searchBar.text)
}
我收到了这条消息
swift:40:58: 'search_options' is not a subtype of 'String'
答案 0 :(得分:11)
查找特定对象的索引:
if let index = find(myArray, objectIAmLookingFor) {
// found! do something
}
过滤器阵列:
let filteredArray = filter(myArray) { $0 == objectIAmLookingFor }
答案 1 :(得分:3)
经过长时间的搜索我没有!, 我正在寻找一种方法来进行动态搜索,就像String包含
的数组一样"hello","lo","yes"
我希望获得包含的所有字符串,例如“lo” 我想得到“你好”和“lo”
所以我找到的最好的方法是正则表达式搜索
所以我做一个For循环抛出Array中的所有选项,并将每个单个对象变量与模式进行比较,并将其保存在对象的新数组中
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) )
}
}
这里最好的部分你可以使用正则表达式的所有好处,并拥有你的旧数组的副本,如果你需要它。
感谢每一位人士的帮助。
答案 2 :(得分:2)
因为filter
接受一个函数,它将给定Array
的每个元素映射到Bool
值(以确定应该过滤掉哪个值),在您的情况下它可能就是这样;
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")]
答案 3 :(得分:2)
正确的答案是
func searchBarSearchButtonClicked( searchBar: UISearchBar!)
{
let filteredArray = filter(search_options_array) { $0.option == "test" }
println(searchBar.text)
}
或
func searchBarSearchButtonClicked( searchBar: UISearchBar!)
{
let filteredArray = filter(search_options_array) { $0.id == "test" }
println(searchBar.text)
}
您必须检索执行搜索的搜索对象的属性