Let’s suppose I have an Int like 30, how can i take ranged numbers by 7 and put them into a list of pairs in Swift?
For example in this case it would be [(1, 7), (8, 14), (15, 21), (22, 28), (29, 30)] where the last couple is 29-30.
I found a code in Kotlin that may do that but I don’t know how could it be in Swift since I don’t know Kotlin. I post it in case it is helpful.
val myInt = 28
val list = (1..ceil(myInt/7.0).toInt()).mapIndexed { index, i ->
7*index + 1 to (7*index + 7).coerceAtMost(myInt)
}
print(list)
Update:
I tried this code so far:
var days = 30
var daysInt: [Int] = []
var index = 0
for i in 1...days {
if index <= days {
if i == 1 {
index += 1
daysInt.append(index)
index += 6
daysInt.append(index)
} else {
index += 1
daysInt.append(index)
index += 6
daysInt.append(index)
}
}
}
And the output is:
- 0 : 1
- 1 : 7
- 2 : 8
- 3 : 14
- 4 : 15
- 5 : 21
- 6 : 22
- 7 : 28
- 8 : 29
- 9 : 35
All fine but the 35 should be 30.
I’m sure there is a better way.
>Solution :
The Kotlin code
(1..myInt step 7).map { it to min(it + 6, myInt) }
which was suggested in a comment can almost literally be translated to Swift.
With stride() you can create the sequence 1, 8, 15, …, 29, and with map() you can map each value to a tuple:
let days = 30
let list = stride(from: 1, to: days, by: 7).map { ($0, min($0+6, days)) }
print(list)
// [(1, 7), (8, 14), (15, 21), (22, 28), (29, 30)]