Swift filter array using NSPredicate

◇◆丶佛笑我妖孽 提交于 2019-12-05 07:45:49

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
}

If you convert the NSArray into a Swift Array, you can use Swift's Array.filter method. Here's an example with simpler objects for clarity:

let arrObjc: NSArray = ["aaa", "bab", "bbb", "baa", "cbc"]
let arr: [AnyObject] = arrObjc //create a swift array with same data

// filter takes a block that returns a boolean. True: keep the item, False: drop it.
arr.filter{
  if let s = $0 as? String {  // first try to cast AnyObject to our expected type.
    return contains(s, "a")   // return true if we want this item, false otherwise.
  } else {
    return false              // this object is of the wrong type, return false.
  }
}

// returns: ["aaa", "bab", "baa"]

Your test at the last line in Objective-C will return if firstName is nil or if lastName is nil. In your swift code, you are just trying to compare two strings as if they were Bools. Instead, you want to return if firstName exists, so you should instead do this in both your objective-c and Swift code:

return firstName != nil
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!