How to return some Enum.type from switching nested Enum?

Viewed 63

I'm very new to swift and trying to make Unit Conversion App. I use nested enums for all units available:

protocol UnitProtocol {

}

enum Units: String, CaseIterable, UnitProtocol {
  case temperature, length, time, volume
  enum Temperature: String, CaseIterable, UnitProtocol {
    case celsius, fahrenheit, kelvin
  }
  enum Length: String, CaseIterable, UnitProtocol {
    case meters, kilometers, feet, yards, miles
  }
  enum Time: String, CaseIterable, UnitProtocol {
    case seconds, minutes, hours, days
  }
  enum Volume: String, CaseIterable, UnitProtocol {
    case milliliters, liters, cups, pints, gallons
  }
}

The user is asked what units to convert with this section:

struct ContentView: View {
  @State private var units = Units.temperature
...

var body: some View {
    NavigationView {
      Form {
        Section {
          Picker("Units to convert", selection: $units) {
            ForEach(Units.allCases, id: \.self) {
              Text($0.rawValue.capitalized)
            }
          }
        }
      }
    }
  }
}

After choosing case from Units enum, I want to display .allCases from selected nested Enum. For example: I chose temperature, so after that I'll iterate with forEach on Units.Temperature.allCases. But how can I make this? I tried to create new variable just below the State property:

  @State private var units = Units.temperature
  private var unit: UnitProtocol {
    switch units {
    case .temperature:
      return Units.Temperature.Type
    case .time:
      return Units.Time.Type
    case .length:
      return Units.Length.Type
    case .volume:
      return Units.Volume.Type
    }
  }

and in the body use this

Section {
          Picker("Convert from", selection: $units) {
            ForEach(unit.allCases, id: \.self) {
              Text($0.rawValue.capitalized)
            }
          }
        }

Sadly, that didn't work for me. What should I do? I would be very glad for every answer

P.S. Sorry for my English, it's not my native language

0 Answers
Related