Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading