使用NSPredicate的Swift过滤器数组 [英] Swift filter array using NSPredicate
问题描述
我有一个用Swift编写的应用程序,它从地址簿中提取用户联系人。
I have an application written in Swift that is pulling in the users contacts from their address book.
我想过滤掉只包含公司名称的联系人(以便让您假设真人联系而不是商家)
I want to filter out the contact that only contain a company name (so that you get your "assumed" real person contact and not businesses)
以下是我在app的Objective-C版本中实现的目标:
Here is how this is being accomplish in the Objective-C version of my app:
NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id person, NSDictionary *bindings) {
NSString *firstName = CFBridgingRelease(ABRecordCopyValue((__bridge ABRecordRef)person, kABPersonFirstNameProperty));
NSString *lastName = CFBridgingRelease(ABRecordCopyValue((__bridge ABRecordRef)person, kABPersonLastNameProperty));
return (firstName || lastName);
}];
NSArray *peopleNotCompanies = [allContacts filteredArrayUsingPredicate:predicate];
这很有效,所以这是我尝试在Swift中做到这一点:
This works perfectly, so here is my attempt to do this in Swift:
var contactList: NSArray = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue()
var predicate: NSPredicate = NSPredicate { (AnyObject person, NSDictionary bindings) -> Bool in
var firstName: String = ABRecordCopyValue(person as ABRecordRef, kABPersonFirstNameProperty).takeRetainedValue() as String
var lastName: String = ABRecordCopyValue(person as ABRecordRef, kABPersonLastNameProperty).takeRetainedValue() as String
return firstName || lastName
})
现在这有几个问题。我在return语句和谓词调用结束时收到这些错误:
Now this has a couple problems. I am getting these errors on the return statement and the end of the predicate call:
如何在Swift的ObjC代码中提供类似的功能?或者有更好的方法在swift中检查联系人是否只有公司名称,然后从最终数组中省略它?
How can I provide similar functionality found in my ObjC code in Swift? Or is there a better way in swift to check if a contact has ONLY a company name and then omit it from the final array?
谢谢!
推荐答案
如果firstName和lastName是可选字符串,则可以将它们与nil进行比较,并在布尔表达式中使用它们。
If you have firstName and lastName be optional strings, you can compare them against nil and use them in a boolean expression.
您的第二个错误是由于关闭后的额外费用。这段代码应该有效。
Your second error is due to the extra paren after your closure. This code should work.
var predicate: NSPredicate = NSPredicate { (AnyObject person, NSDictionary bindings) -> Bool in
var firstName: String? = ABRecordCopyValue(person as ABRecordRef, kABPersonFirstNameProperty).takeRetainedValue() as? String
var lastName: String? = ABRecordCopyValue(person as ABRecordRef, kABPersonLastNameProperty).takeRetainedValue() as? String
return firstName != nil || lastName != nil
}
这篇关于使用NSPredicate的Swift过滤器数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!