问题
I am filtering a CNContact
phoneNumbers
to see if dialed number is contained within the contact's
number. Bellow attached code works fine, but.....
My problem: If the phone number has no white spaces inside, works ok but if I search "0761" and contact's phone number is "076 1", it ignores it.
I am using NSPredicate
. Code:
func filterAndGetCurrentPhoneNumber(c: CNContact) -> String{
let searchPredicate = NSPredicate(format: "SELF.value.stringValue CONTAINS[c] %@", self.txtf_dial.text!)
let array = (c.phoneNumbers as NSArray).filteredArrayUsingPredicate(searchPredicate)
if array.count > 0{
let str: String? = ((array[0] as! CNLabeledValue).value as! CNPhoneNumber).stringValue
if str != nil {
return str!;
}
}
return ""
}
How can I modify NSPredicate
to ignore whitespaces in swift?
回答1:
NSPredicate
has no such search option, so you'd need to perform the filtering yourself. Instead of going to predicateWithBlock:
, though, you might as well stick to the Swift standard library.
// an extension to make the string processing calls shorter
extension String {
func numericString() -> String {
// split and rejoin to filter out the non-numeric chars
let set = NSCharacterSet.decimalDigitCharacterSet().invertedSet
return self.componentsSeparatedByCharactersInSet(set).joinWithSeparator("")
}
}
// your function
func filteredPhone(c: CNContact, filterText: String) -> String {
// conform the query string to the same character set as the way we want to search target strings
let query = filterText.numericString()
// filter the phone numbers
let filtered = c.phoneNumbers.filter({ val in
let phone = (val.value as! CNPhoneNumber).stringValue
// conform the target string to numeric characters only
let conformed = phone.numericString()
return conformed.containsString(query)
})
if let result = filtered.first?.value as? CNPhoneNumber {
return result.stringValue
} else {
return ""
}
}
// test case
let contact = CNMutableContact()
contact.phoneNumbers = [CNLabeledValue(label: CNLabelHome, value: CNPhoneNumber(stringValue: "867-5309"))]
filteredPhone(contact, filterText: "753")
By the way... I left the interface to your function largely unchanged. But unless it's important to use the empty string as this function's result in the UI, it's generally better to use an Optional return value to indicate a lack of search result — that way code that calls this function can tell the difference between a search that returns no result and a search whose result is the empty string.
来源:https://stackoverflow.com/questions/34320433/how-can-i-modify-nspredicate-to-ignore-whitespaces-in-swift