简体   繁体   中英

How to convert ClosedRange<Int> to ClosedRange<Double> in Swift

I have a ClosedRange passed in as a parameter, and now I need to convert it to a ClosedRange:

  let range: ClosedRange<Int>
  
  init(range: ClosedRange<Int>) {
    self.range = range
  }


  var body: some View {
    Slider(value: doubleBinding, in: range.startIndex...range.endIndex, step: 1)
  }

The Slider init function takes a ClosedRange argument. So I got this error:

Cannot convert value of type 'ClosedRange<Int>.Index' to expected argument type 'Double'

So I tried this:

  let min = Double(Int(range.startIndex))
  let max = Double(Int(range.endIndex))
  Slider(value: doubleBinding, in: min...max, step: 1)

But got this error:

Initializer 'init(_:)' requires that 'ClosedRange<Int>.Index' conform to 'BinaryInteger'

You've used the wrong property. It's not startIndex and endIndex . It's lowerBound and upperBound :

Slider(value: doubleBinding, 
       in: Double(range.lowerBound)...Double(range.upperBound), 
       step: 1)

You can write a ClosedRange initialiser that conveniently does this:

extension ClosedRange {
    init<Other: Comparable>(_ other: ClosedRange<Other>, _ transform: (Other) -> Bound) {
        self = transform(other.lowerBound)...transform(other.upperBound)
    }
}

Usage:

Slider(value: doubleBinding, 
       in: ClosedRange(range, Double.init), 
       step: 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM