Search code examples
swiftfiltercastingmapping

How do I filter an array of a class in swift that returns an array of a subclass of the original class?


How do I filter an array of objects of a certain class and return the results to an array of of a subclass of the original class? Specifically to filter and array of CKRecord and return the results to an array of [CKShare], like thus:

let records = [CKRecord]()

let shares: [CKShare] = records.filter({ $0 is CKShare })

The code above generates a code-time error message "Cannot assign value of type '[CKRecord]' to type '[CKShare]'".

I wonder if I could use a map method to work with the filter method to do what I want to do, or a version of the map method.


Solution

  • Use compactMap for this.

    let shares = records.compactMap({ $0 as? CKShare })
    

    If you want to filter also your records then you can write like this.

    //Replace $0.isEnable with your condition, if that is true then cast it for sub class CKShare else return nil
    let shares = records.compactMap({ $0.isEnable ? $0 as? CKShare : nil })