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

时间:2017-04-02 07:36:30

标签: ios swift3 nsarray

我正在使用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 ($0 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)
    }

}

提前致谢

2 个答案:

答案 0 :(得分:1)

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

例如,location应声明为:

var locations: [roommodel] = []

并列为

var list: [roommodel] = []

(你应该用camelcase RoomModel命名类。)

然后可以将过滤简化为:

let filtered = list.filter {
    return ($0.name ?? "").hasPrefix(searchText)
}

或者,对于“包含”搜索:

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

有更复杂的选项:

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

答案 1 :(得分:0)

试试这个

let filtered  = list.filter(){

        return ($0 as AnyObject).contains("2.1") // 2.1 or searchtext

        }
        print(filtered)