ios – 使用NSPredicate的Swift过滤器阵列

前端之家收集整理的这篇文章主要介绍了ios – 使用NSPredicate的Swift过滤器阵列前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个用 Swift编写的应用程序,它从他们的地址簿中提取用户联系人.

我想过滤掉只包含公司名称的联系人(这样你就可以得到“假定的”真人联系而不是商家)

以下是我在app的Objective-C版本中实现的方法

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中做到这一点:

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语句和谓词调用结束时收到这些错误

如何在Swift中的ObjC代码中提供类似的功能?或者有更好的方法在swift中检查联系人是否只有公司名称,然后从最终数组中省略它?

谢谢!

解决方法

如果firstName和lastName是可选字符串,则可以将它们与nil进行比较,并在布尔表达式中使用它们.

你的第二个错误是由于关闭后额外的paren.这段代码应该有效.

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
}

猜你在找的iOS相关文章