Difference between println and print in Swift
Asked Answered
H

5

10

The use of println and print in Swift both print to the console. But the only difference between them seems to be that println returns to the next line whereas print will not.

For example:

println("hello world")
println("another world")

will output the following two lines:

hello world
another world

while:

print("hello")
print("world")

outputs only one line:

helloworld

The print seems to be more like the traditional printf in C. The Swift documentation states that println is the equivalent to NSLog but what's the purpose of print, is there any reason to use it other than not returning to the next line?

Heathheathberry answered 6/6, 2014 at 1:24 Comment(1)
This naming is very familiar to those coming from Java. The "LN" in println stands for "line".Litter
R
33

In the new swift 2, the println has been renamed to print which as an option "terminator" argument.

(udpated 2015-09-16 with the new terminator: "")

var fruits = ["banana","orange","cherry"]

// #1
for f in fruits{
    print(f)
}

// #2
for f in fruits{
    print("\(f) ", terminator: "")
}

#1 will print

banana
orange
cherry

#2 will print

banana orange cherry 
Reactive answered 11/6, 2015 at 16:45 Comment(3)
This should be marked the correct answer since the spec has changed with the release of Swift 2.Avesta
This seems to have changed. /// - Note: to print without a trailing newline, pass 'terminator: "" Looks like the new line is now the default and appendNewLine has been removed.Eparchy
As in the new swift 2 just released, the println has been renamed to print. There are no printlns anymore. just print.Pallmall
Z
5

That's exactly what it is, it's used when you want to print multiple things on the same line.

Zampardi answered 6/6, 2014 at 1:29 Comment(1)
Could you provide an example of why you would use print instead of println?Heathheathberry
H
2

Exactly like you said, to print without adding a new line. There are some cases where you may want this. This is a simple example:

var arr = [1,2,3,4,5]

print("My array contains: ")
for num in arr{
    print("\(num) ")
}
Hakenkreuz answered 6/6, 2014 at 1:27 Comment(0)
C
1

It is same as in Java print is just print where ln in println means "Next Line". It will create a next line for you.

Chiller answered 14/5, 2017 at 11:26 Comment(1)
Your answer is obsolete, the syntax has changed, see Jeremy Chone's answer.Foltz
G
0

The deference between print and println is that after print prints the cursor does not skip lines and after println prints the cursor skips a line

Geyer answered 22/9, 2016 at 21:18 Comment(1)
That was the case until Swift 2. Now the syntax has changed, see Jeremy Chone's answer.Foltz

© 2022 - 2024 — McMap. All rights reserved.