我有这样的Hero对象:
import Foundation
import UIKit
class Hero {
var name: String!
var image: UIImage? {
return UIImage(named: "\(name)")!
}
required init(name: String) {
self.name = name
}
}
我想在搜索栏上搜索英雄,这是我的搜索功能:
func filterContentForSearchText(searchText:String) {
let searchBarTemp = searchBar
heroesFiltered = heroes.filter { (hero) -> Bool in
if hero.name.lowercaseString == searchBarTemp!.text?.lowercaseString {
return true
}
return false
}
}
但是当我搜索它时根本没有过滤,当我更改searchBar中的文本时,数组是空的。
我也尝试使用NSPredicate进行搜索:
func filterContentForSearchText(searchText:String) {
heroesFiltered = []
let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", self.searchBar!.text!)
let array = (heroes as NSArray).filteredArrayUsingPredicate(searchPredicate)
heroesFiltered = array as? [Hero]
}
但它在这一行崩溃了:
let array = (heroes as NSArray).filteredArrayUsingPredicate(searchPredicate)
答案 0 :(得分:0)
我试过这样的话:
heroesFiltered = heroes.filter({ (hero) -> Bool in
let nameText: NSString = hero.name
return (nameText.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch).location) != NSNotFound
})
它有效。