问题
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