我正在过滤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
以忽略swift中的空格?
答案 0 :(得分:1)
NSPredicate
没有此类搜索选项,因此您需要自行执行过滤。不过,不要去predicateWithBlock:
,你也可以坚持使用Swift标准库。
// 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")
顺便说一下......我把界面留给你的功能基本没变。但是,除非使用空字符串作为此函数在UI中的结果非常重要,否则通常最好使用Optional返回值来表示缺少搜索结果 - 那样的代码就是调用此函数可以区分不返回结果的搜索和结果为空字符串的搜索。
答案 1 :(得分:0)
您可以使用trimmingCharacters()
trim —从开头删除空格(或其他字符),然后 字符串的结尾。
例如:“ hello” ==“ hello” ==“ hello” ==“ hello”
“ hello world” ==“ hello world” ==“ hello world” ==“ hello world”
string.trimmingCharacters(位于:.whitespacesAndNewlines中)