Swift nested filter optimization?

前端 未结 2 1370
迷失自我
迷失自我 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.

提交回复
热议问题