Reputation: 172
I have an array of ClosedRange
Double
s as follows:
var ranges = [ClosedRange<Double>]()
Is there a swifty way to retrieve the average of each ClosedRange
without having to iterate over each element in the array, and then each number in each ClosedRange
?
For example, if the array is:
[ClosedRange(1...3), ClosedRange(4...5)]
I would like to retrieve: 2, 4.5
Upvotes: 0
Views: 128
Reputation: 236458
You just need to coerce lower and upper bounds to Double, sum them and then divide by two:
let ranges = [1...3, 4...5]
let avgs = ranges.map {
(Double($0.lowerBound) + Double($0.upperBound)) / 2
}
print(avgs) // "[2.0, 4.5]\n"
If your range's bounds are already Doubles:
let ranges = [1.0...3.0, 4.0...5.0]
let avgs = ranges.map {
($0.lowerBound + $0.upperBound) / 2
}
print(avgs) // "[2.0, 4.5]\n"
Upvotes: 2