Reputation: 4886
I have an Array
of Int
and want to find what range each instance is in.
let array: [Int] = [35,34,33,32,31,30,28,27,26,25,24,23,7,6,5,4,3,2,1]
I have another Array
of Tuple's
of Int
let tupleArray: [(Int, Int)] = [(35,30),(28,22), (21,15), (14,8), (7,0)]
I am using a Switch
to iterate over them.
for a in 0..<array.count {
var iteration: Int = 0
switch array[a] {
case tupleArray[iteration].0...tupleArray[iteration].1:
print("Within Range")
default:
print("Next iteration")
repeat {
iteration++
} while tupleArray[iteration].0 < array[a]
}
}
My question is how can I make it so that there is just that one case and then in the default it keeps going until it finds the range that the next number would fall into. The current code works completely find until there is a gap of more than iteration. So for 35-30 and 28-23 it works fine but then it goes to 21-15
Upvotes: 2
Views: 631
Reputation: 93151
I'm surprised that you can run the code at all. In my Xcode 7.1, it gives a runtime error:
fatal error: Can't form Range with end < start
...because your tuples are in (end, start)
form rather than the other way around.
If you want to find what range each item in array
belong to, try this:
for a in array {
if let range = (tupleArray.filter { $0.1 <= a && a <= $0.0 }).first {
print("\(a) is within \(range)")
} else {
print("Cannot find a range for \(a)")
}
}
Upvotes: 1