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'
CodePudding user response:
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)