gpt4 book ai didi

ios - 如何修改 NSPredicate 以忽略 Swift 中的空格?

转载 作者:行者123 更新时间:2023-11-29 01:23:27 24 4
gpt4 key购买 nike

我正在过滤 CNContact phoneNumbers 以查看调用的号码是否包含在 联系人的 号码中。波纹管附件代码工作正常,但是.....

我的问题:如果电话号码里面没有空格,工作正常,但如果我搜索“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 中忽略空格?

最佳答案

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 中使用空字符串作为此函数的结果很重要,否则通常最好使用可选返回值来指示缺少搜索结果——这样调用此函数的代码可以区分返回的搜索没有结果和结果为空字符串的搜索。

关于ios - 如何修改 NSPredicate 以忽略 Swift 中的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34320433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com