Multiple instances of println() vs. a single instance

Hey all, I'm going through some Swift learning materials (https://www.weheartswift.com) and learning the basics of coding in Swift. I recently came to an exercise in looping (exercise # 4.4 on https://www.weheartswift.com/loops/) in which the tutorials says:


Write all the numbers from 1 to

N
in alternative order, one number from the left side (starting with one) and one number from the right side (starting from
N
down to 1).

It gives the example of:
var N = 4

output:

1

4

2

3

In the Playground in Xcode if I use the following code, it shows the println() output on two separate lines, presumably because I have two separate println()'s:


// bigNum is what I am using in place of the "N" used in the example

var bigNum = 5

var topDown = bigNum

var bottomUp = 1


for x in 1...bigNum {

if x % 2 != 0 {

println(bottomUp)

++bottomUp

} else {

println(topDown)

--topDown

}

}


However, if I use the following slightly lengthier code, I am able to put the outputs in one place, and in the correct (I think!) order:


// bigNum is what I am using in place of the "N" used in the example

var bigNum = 5

var topDown = bigNum

var bottomUp = 1

var output = 1

for x in 1...bigNum {

if x % 2 != 0 {

output = bottomUp

bottomUp = bottomUp + 1

} else {

output = topDown

topDown = topDown - 1

}

println(output)

}


My Question: In the real world (read: a real program) does it make a difference which of these I use? Will the first example print properly and with the numbers in the order that this exercise is trying to achieve? Or in order to have the numbers print out in one place in the proper order will I need to use something like the second example?


Thank you very much for humoring a Swift N00b.

🙂,

Wagulous

P.S. if you have some suggestions on making my code more elegant in general, I always appreciate the edification 🙂!

P.P.S. I'm using Xcode 6.4.

No difference. Each of your codes are executed sequencially, so println is invoked 5 times. The number of appearnces in your code is irrelevant.

Your 2 version is considered clearer code by many, but for the compiler and the generated code there is no difference.

Thank you for the helpful answer 🙂 -- If that is the case, is there any way in the Playground to see the output as it would actually appear, instead of line-by-line? Or is that outside the scope of functionality for Playgrounds?

In Xcode 6.x, you need to open Assistant Editor.

View > Assistant Editor > Show Assistant Editor

Thank you!

Multiple instances of println() vs. a single instance
 
 
Q