SwiftUI: @Binding Type Conversion

What can you do if a @Binding var has a different type from the @State var you want to bind to it?

For example, say you have a Slider which you bind to a Double state var, and you want to bind the same state var to an Int in another View:

struct MyView: View {
    @State private var currentStep: Double = 0.0
 
    var body: some View {
        Slider(value: $currentStep, in: 0.0 ... 9.0, step: 1.0)
        ViewWithInt(bindingInt: $currentStep) // Error: 'Binding<Double>' is not convertible to 'Binding<Int>'
    }
}

Solution: define an Int property on Double:

extension Double {
     var int: Int {
         get { Int(self) }
         set { self = Double(newValue) }
     }
 }

Then you can bind this int property:

ViewWithInt(bindingInt: $currentStep.int) // Works

1 thought on “SwiftUI: @Binding Type Conversion

  1. Hey, this actually helped! I was looking for a clean-ish way to get a slider to represent integers and this did the trick. Thank you!

Leave a Reply