How to convert the following expression to swift 3 code
for w = 0; CDay >= month[0][w] + 1; ++w
{
CDay = CDay - month[0][w]
CMonth = w + 2
}Thanks in advance
How to convert the following expression to swift 3 code
for w = 0; CDay >= month[0][w] + 1; ++w
{
CDay = CDay - month[0][w]
CMonth = w + 2
}Thanks in advance
I would try something like this (there is surely a much cleaner way to to this)
var stop = false
var w = 0
while !stop {
w += 1
if w >= month[0].count { // otherwise, risk of index overflow
stop = true
} else {
stop = cDay >= month[0][w]
cDay -= month[0][w]
}
cMonth = w + 2
}
Note : your example shows that C-style allows for very condensed code, but alos how complex it is to understand exactly how the loop behaves and what is the intent of the code.
and for the naming, what is w ? cMonth = w + 2 let hint it's a month, but that doesn't mean anything in month[0][w]
And there is a risk to overflow month[0]
That helps.
Thank you !
A for-loop statement of the form:
for init; condition; increment {
do something
}
can be translated to this while-loop:
init
while condition {
do something
increment
}
So, for your example:
var w = 0
while CDay >= month[0][w] + 1 {
CDay = CDay - month[0][w]
CMonth = w + 2
w += 1
}Note that Swift programmers normally name variables and constants with an initial lower-case letter:
var w = 0
while cDay >= month[0][w] + 1 {
cDay -= month[0][w]
cMonth = w + 2
w += 1
}