如何修改 NSPredicate 以忽略 Swift 中的空格? [英] How can I modify NSPredicate to ignore whitespaces in Swift?
问题描述
我正在过滤 CNContact
phoneNumbers
以查看拨打的号码是否包含在 contact's
号码中.波纹管附加代码工作正常,但是......
I am filtering a CNContact
phoneNumbers
to see if dialed number is contained within the contact's
number. Bellow attached code works fine, but.....
我的问题:如果电话号码里面没有空格,工作正常,但如果我搜索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 中忽略空格?
How can I modify NSPredicate
to ignore whitespaces in swift?
推荐答案
NSPredicate
没有这样的搜索选项,因此您需要自己执行过滤.不过,与其使用 predicateWithBlock:
,不如坚持使用 Swift 标准库.
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")
顺便说一下...我保留了您功能的界面,但基本上没有变化.但是,除非在 UI 中使用空字符串作为此函数的结果很重要,否则通常最好使用 Optional 返回值来指示缺少搜索结果 - 这样调用此函数的代码可以区分返回的搜索无结果且搜索结果为空字符串.
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.
这篇关于如何修改 NSPredicate 以忽略 Swift 中的空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!