0

I would like to be able to pass the GaugeStyle for a Gauge as a parameter to my own SwiftUI view, however I can't seem to get this to work with the compiler. When I try the below code I get an error, Type 'any View' cannot conform to 'View'.

import SwiftUI

struct MyGauge: View {
    let min = 0.0
    let max = 10.0
    let current = 5.0
    let style: any GaugeStyle = .accessoryCircular
            
    var body: some View {
        Gauge(value: current, in: min...max) {
            Text("Gauge")
        } currentValueLabel: {
            Text("\(current)")
        } minimumValueLabel: {
            Text("\(min)")
        } maximumValueLabel: {
            Text("\(max)")
        }
        .gaugeStyle(style)
    }
}

(Code is simplified for brevity.)

What's the correct way to allow a GaugeStyle to be passed around?

stanlemon
  • 399
  • 3
  • 10

1 Answers1

1

SwiftUI requires concrete types for most areas of a View especially wrappers and view modifiers.

The any keyword is "existential"

@available(iOS 16.0, *)
struct MyGauge<G>: View where G : GaugeStyle{
    let min = 0.0
    let max = 10.0
    let current = 5.0
    let style: G
    init(style: G = .accessoryCircular){
        self.style = style
    }
    var body: some View {
        Gauge(value: current, in: min...max) {
            Text("Gauge")
        } currentValueLabel: {
            Text("\(current)")
        } minimumValueLabel: {
            Text("\(min)")
        } maximumValueLabel: {
            Text("\(max)")
        }
        .gaugeStyle(style)
    }
}

@available(iOS 16.0, *)
struct MyGauge_Previews: PreviewProvider {
    static var previews: some View {
        MyGauge()
        MyGauge(style: .accessoryLinear)
    }
}
lorem ipsum
  • 21,175
  • 5
  • 24
  • 48
  • Pefect, thank you! Is there any way to default the parameter inline to its definition or must it be done via the init() method? – stanlemon Nov 28 '22 at 01:24
  • 1
    @stanlemon no since it is being "inferred" Swift needs to know the value first, variables are not initialized in order – lorem ipsum Nov 28 '22 at 12:39