我正在过滤CNContact
phoneNumbers
,以查看拨号号码是否包含在contact's
号码中。波纹管附加代码工作正常,但是........
我的问题:如果电话号码内部没有空格,可以正常工作,但是如果我搜索“ 0761”并且联系人的电话号码为“ 076 1”,它将忽略它。
我正在使用NSPredicate
。代码:
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 ""
}
如何修改NSPredicate
以迅速忽略空格?
NSPredicate
没有此类搜索选项,因此您需要自己执行过滤。不过,您最好还是坚持使用Swift标准库,而不是转到predicateWithBlock:
。
// 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")
顺便说一下,我在很大程度上不改变您函数的接口。但是,除非在用户界面中使用空字符串作为此函数的结果很重要,否则通常最好使用Optional返回值来表示缺少搜索结果-调用此函数的代码可以告诉返回搜索的区别没有结果,并且搜索结果为空字符串。
您可以使用trimmingCharacters()
trim-从开头删除空格(或其他字符),然后字符串的结尾。
例如:“ hello” ==“ hello” ==“ hello” ==“ hello”
“” hello world“ ==” hello world“ ==” hello world“ ==” hello world“
string.trimmingCharacters(in:.whitespacesAndNewlines)