我定义的结构如下:
struct ECUnifiedStructure{
var contactName : String!
var contactNumber = [String]()
...
...
init(contact: CNContact , EProfile : Bool) {
let validTypes = [
CNLabelPhoneNumberiPhone,
CNLabelPhoneNumberMobile,
CNLabelPhoneNumberMain,
CNLabelHome,
CNLabelWork
]
var givenName = contact.givenName + " " + contact.middleName
let familyName = contact.familyName
if (givenName == "" && familyName == "") || givenName == " "{
givenName = contact.organizationName
}
self.contactName = givenName.capitalized + familyName.capitalized
self.contactNumber = contact.phoneNumbers.compactMap({ (PhoneNumber) -> String? in
if let phoneLabel = PhoneNumber.label , validTypes.contains(phoneLabel){
return PhoneNumber.value.stringValue.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "-", with: "")
}
return nil
})
....
....
....
}}
问题陈述:需要根据名称和电话号码过滤ECUnifiedStructure数组(即[ECUnifiedStructure])(检查子字符串和整个字符串)。
当前实现:以下是我已经完成的当前实现。这里的触点和过滤器触点都是[ECUnifiedStructure]。
self.filterContacts = self.contacts.filter {($0.contactName).range(of: textString, options: [ .caseInsensitive, .diacriticInsensitive ]) != nil} + self.contacts.filter {($0.contactNumber.compactMap {$0}.contains(textString))}
实现问题:获取用于按预期过滤联系人姓名的结果,结果包括整个字符串和子字符串,但
过滤电话号码时,找不到子字符串的结果 找不到。只有当我们给出完整的电话号码时,结果才会出现。
可能的原因:
self.contacts.filter {($0.contactNumber.compactMap {$0}.contains(textString))}
例如:假设联系人= [[姓名:“ David”,电话号码: [“ 1234567890”,9876543210]],[名称:“希尔顿”,电话号码: [“ 1011111111”,“ 2222222222”]],[名称:“刘易斯”,电话号码: [“ 1111111111”,“ 2222222222”]]]
searchString =“ 10”
预期结果= [[name:“ David”,phoneNumber: [“ 1234567890”,9876543210]],[名称:“希尔顿”,电话号码: [“ 1011111111”,“ 2222222222”]]]
当前结果=空。
请提出一种优雅的方法。如果可以,请指出我做错了什么。预先感谢。
答案 0 :(得分:1)
这将返回电话号码包含“ 10”的所有struct对象
let result = contacts.filter{ $0.phoneNumber.contains(where: { $0.contains("10")}) }
使用原始过滤器代码
self.filterContacts = self.contacts.filter {($0.contactName).range(of: textString, options: [ .caseInsensitive, .diacriticInsensitive ]) != nil} + self.contacts.filter { $0.contactNumber.contains(where: {$0.contains(textString)})}
这是我完整的测试代码
struct ECUnifiedStructure{
var name : String!
var phoneNumber = [String]()
}
let contacts:[ECUnifiedStructure] = [ECUnifiedStructure(name: "David" , phoneNumber : ["1234567890","9876543210"]),
ECUnifiedStructure(name: "Hilton" , phoneNumber : ["1011111111","2222222222"]) ,
ECUnifiedStructure(name: "lewis" , phoneNumber : ["1111111111","2222222222"])]
let result = contacts.filter{ $0.phoneNumber.contains(where: { $0.contains("10")}) }
for r in result {
print(r)
}
输出
ECUnifiedStructure(name: Optional("David"), phoneNumber: ["1234567890", "9876543210"])
ECUnifiedStructure(name: Optional("Hilton"), phoneNumber: ["1011111111", "2222222222"])