I'm trying to filter data from 2d array according to the string/text which is entered by user like if we write the name or phone number of a person it contact detail is searched and shown.
In 2D array [["Name","Phone number"]]. if number or name which is entered by the user is matched with any value then that will store in an other array.
var data : [[String]] = [["AB","+923476760226"],["Umair","+923366111830"],.......]
The way to filter a 2D array is to filter twice, once per level.
var data = [["AB","+923476760226"],["Umair","+923366111830"]]
let searchString = "+9234"
var result = data.filter { (dataArray:[String]) -> Bool in
return dataArray.filter({ (string) -> Bool in
return string.containsString(searchString)
}).count > 0
}
This code just filters out all the items that has at least one item that contains the searchString.
However, I'd like to say that you really should keep the name and number in a separate class or struct and build some mach function so that you don't have to filter twice
struct Contact{
let name: String
let number: String
init(name: String, number:String) {
self.name = name
self.number = number
}
func match(string:String) -> Bool {
return name.containsString(string) || number.containsString(string)
}
}
let properData = [Contact(name: "AB", number: "+923476760226"), Contact(name: "Umair", number: "+923366111830")]
let properResult = properData.filter { (contact) -> Bool in
return contact.match(searchString)
}
This will make your code a bit cleaner in the long run and it's a good idea to work with classes and struct like this in general
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加