如何在 NSObject Swift 3.0 的 NSArray 中搜索字符串?

How to search string in NSArray of NSObject Swift 3.0?

我正在研究 UiSearchbar,如果用户输入一些字符串,我必须向他展示相关的建议。现在数组包含如下格式的数据:

"Name: Optional(\"2.1 - Classroom\")",
"Name: Optional(\"2.11 - Classroom\")",
"Name: Optional(\"2.22 - Classroom\")",
"Name: Optional(\"2.13 - Classroom\")",
"Name: Optional(\"2.34 - Classroom\")",
"Name: Optional(\"2.55 - Classroom\")"

我想做的是,当用户键入 2.1 时,我想建议他所有名称都以 2.1 开头。我已经尝试了从互联网上获得的所有建议。但是,我是 iOS 的新手,所以我不知道该怎么做。 这是我的代码:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String){
    if searchText.characters.count == 0{
        isSearch = false;
        self.resulttableview.reloadData()
    }else{
        let filtered  = list.filter(){
            return ([=12=] as AnyObject).contains(searchText) // 2.1 or searchtext
        }
        print(filtered)
    }
}

为数组赋值

func itemsDownloaded(items: NSArray){
    list = items
    self.resulttableview.reloadData()
}

此代码用于从 JSON 检索数据并存储在可变数组中:

func downloadItems(){
    let url = NSURL(string: urlPath)!

    var session: URLSession!
    let configuration = URLSessionConfiguration.default

    session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    let task = session.dataTask(with: url as URL)

    task.resume()
}

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data){
    self.data.append(data);
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?){
    if error != nil{
        print("Failed to download data")
    }else{
        print("Data downloaded")
        self.parseJSON()
    }
}

func parseJSON(){
    var jsonResult: NSMutableArray = NSMutableArray()

    do{
        let jsonResults = try JSONSerialization.jsonObject(with: self.data as Data , options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray
        jsonResult = jsonResults.mutableCopy() as! NSMutableArray
    }catch let error as NSError{
        print(error)
    }

    var jsonElement = NSDictionary()
    let locations: NSMutableArray = NSMutableArray()

    for i in 0 ..< jsonResult.count{
        jsonElement = jsonResult[i] as! NSDictionary
        let location = roommodel()

        if let name = jsonElement["name"] as? String{
            location.name = name
        }

        locations.add(location)
    }

    DispatchQueue.main.async{
        self.delegate.itemsDownloaded(items: locations)
    }

}

提前致谢

试试这个

let filtered  = list.filter(){

        return ([=10=] as AnyObject).contains("2.1") // 2.1 or searchtext

        }
        print(filtered)

首先,不要在Swift代码中使用NSArrayNSMutableArray

例如,location 应声明为:

var locations: [roommodel] = []

并列为

var list: [roommodel] = []

(你应该用驼峰命名 类 RoomModel)。

那么过滤可以简化为:

let filtered = list.filter {
    return ([=12=].name ?? "").hasPrefix(searchText)
}

或者,对于 "contains" 搜索:

let filtered = list.filter {
    return ([=13=].name ?? "").range(of: searchText) != nil
}

具有更复杂的选项:

let filtered = list.filter {
    return ([=14=].name ?? "").range(of: searchText, options: [.caseInsensitive, .diacriticsInsensitive]) != nil
}