How to write this code in swift 3.0. using For loop?
for (int index = 0; index < 100; index += (1 + index)) {
printf("%d\t",index);
}
How to write this code in swift 3.0. using For loop?
for (int index = 0; index < 100; index += (1 + index)) {
printf("%d\t",index);
}
You increment is increasing. Since the C-style for loop isn't available, you might use code like this:
var index = 0
while index < 100 {
print("\(index)", terminator: "\t")
index += 1 + index
}
print("")
You could also write this code in functional style:
for f in sequence(first: 0,
next: {
$0 + $0 + 1
})
.prefix(while: {$0 < last}) {
print(f, terminator: "\t")
}
print("")
(The prefix function requires Swift 3.1)
This kind of for
loop came from C, and counter to the design and spirit of the Swift language. That’s why it was eliminated in Swift 3 (you can find out more about its removal here).
C-style for loops have three statements:
First, there’s the initialization statement, where you set up one or more variables. In this case, the initialization statement is:
int index = 0
which in Swift becomes
var index = 0
Then, there’s the loop invariant, which is a condition that must be true at the very start and end of each pass through the loop. In this case, the loop invariant is:
index < 100
The Swift code is pretty much the same as the C code.
And finally, there’s what I call the change statement, which makes a change to some condition in the loop, which needs to be evaluated to see if another pass needs to be made through the loop. In this case, it’s this statement:
index += 1 + index
Again, the Swift code is pretty much the same as the C code.
You should use a while loop, and the equivalent Swift code looks like this:
while index < 100 {
print("\(index)\t")
index += 1 + index
}
The index += 1 + index
code, while valid, is unusual. Are you sure you wanted that, or did you want the more common index += 1
?
If you must use a for loop, you could use a sequence but that would be more verbose and cumbersome than a while loop:
for index in sequence(first:0, next:{ let index = $0 + $0 + 1; return index < 100 ? index : nil})
{
print("\(index)")
}
You could also generalize this to any type and increments using a generic function:
func cFor<T>(_ start:T, _ condition:@escaping (T)->Bool, _ increment:@escaping (inout T)->()) -> UnfoldSequence<T, (T?, Bool)>
{
return sequence(first:start, next:{ var next = $0; increment(&next); return condition(next) ? next : nil })
}
for index in cFor(0,{$0<100},{$0 += $0 + 1})
{
print("\(index)")
}