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

Optional CaseIterable in swift?

For example:

enum Filter {
  case filter1
  case filter2
  ...
}

let allCases: [Filter?] = [.filter1, .filter2, ..., nil]

The problem is there are could be a lot of cases and CaseIterable returns [Filter] (nonoptional values only). How to solve this issue properly?

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 :

If you make your enum conform to CaseIterable you could easily create an array of optional values

enum Filter: CaseIterable {
  case filter1
  case filter2
}

let allCases: [Filter?] = Filter.allCases + [nil]

or add it as a computed property

extension Filter {
    var optionalValues: [Filter?] {
        Self.allCases + [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