Search code examples
swiftenumsprotocols

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?


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]
        }
    }
    

    or as a computed property in CaseIterable

    extension CaseIterable  {
        static var optionalValues: [Self?] {
            allCases.map(Optional.init) + CollectionOfOne(nil)
        }
    }