UITableView SearchBar filtering inquiry

只谈情不闲聊 提交于 2019-12-23 19:51:28

问题


I have a very long tableView that I am able to search and filter results.

However, if I were to type the letter "i" as input, all words with the letter "i" show up. Is it possible to filter in a way so that the letter I type corresponds to the first letter of the word I want to filter.

For example my array ["should not use","Tristan","biscuit","is","should not use"]

and if I search the word "is"

, can that word automatically show up before the word "biscuit"?

Expected Result : ["is","biscuit","Tristan"]


回答1:


You can use filter and sorted function to get the expected result.

import UIKit

    var theArray: [String] = ["biscuit", "Tristan", "is", "iser", "instrument", "look"]
    var keyword: String = "is"

    let result = theArray
        .filter { $0.contains(keyword) }
        .sorted() { ($0.hasPrefix(keyword) ? 0 : 1) < ($1.hasPrefix(keyword) ? 0 : 1) }


    print(result)

OUTPUT

["is", "iser", "biscuit", "Tristan"]



来源:https://stackoverflow.com/questions/46987207/uitableview-searchbar-filtering-inquiry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!