Swift nested filter optimization?

前端 未结 2 1335
迷失自我
迷失自我 2021-02-10 01:58

I was trying to do something in Swift that would be easy in Objective-C using KVC. The new Contacts framework added in iOS9 is for the most part easier to use than the old Addr

相关标签:
2条回答
  • 2021-02-10 02:24

    If you are looking for a more Swift-y way to do it:

    let matches = contacts.filter {
        return $0.phoneNumbers
                    .flatMap { $0.value as? CNPhoneNumber }
                    .contains { $0.stringValue == JennysPhone }
    }
    

    .flatMap casts each member of phoneNumbers from type CNLabeledValue to type CNPhoneNumber, ignoring those that cannot be casted.

    .contains checks if any of these phone numbers matches Jenny's number.

    0 讨论(0)
  • 2021-02-10 02:28

    I'm guessing you're wanting a more swift-y way, but obviously anything you can do in Obj-C can also be done in swift. So, you can still use NSPredicate:

    let predicate = NSPredicate(format: "ANY phoneNumbers.value.digits CONTAINS %@", "1118675309")
    let contactNSArray = contacts as NSArray
    let contactsWithJennysPhoneNumber = contactNSArray.filteredArrayUsingPredicate(predicate)
    
    0 讨论(0)
提交回复
热议问题