Print in Swift 3

29,112

Solution 1

There is almost no functional difference, the comma simply inputs a space either before or after the string.

let name = "John"

// both print "Hello John"
print("Hello", name)
print("Hello \(name)")

Solution 2

You can use the \(variable) syntax to create interpolated strings, which are then printed just as you input them. However, the print(var1,var2) syntax has some "facilities":

  • It automatically adds a space in between each two variables, and that is called separator
  • You can customise your separator based on the context, for example:

    var hello = "Hello"
    var world = "World!"
    print(hello,world,separator: "|")    // prints "Hello|World!"
    print(hello,world,separator: "\\//")    // prints "Hello\\//World!"
    
Share:
29,112

Related videos on Youtube

BananZ
Author by

BananZ

YOLO

Updated on July 29, 2021

Comments

  • BananZ
    BananZ almost 3 years

    i would like to know what's the different between these two way to print the object in Swift. The result seems identical.

    var myName : String = "yohoo" 
    print ("My name is \(myName).")
    
    print ("My name is ", myName, ".")
    
    • Hamish
      Hamish about 7 years
      One difference is they don't output the same thing – My name is yohoo. vs. My name is yohoo . ;) (there's also double space between "is" and "yohoo" in the latter which isn't rendering here)
    • Eric Aya
      Eric Aya about 7 years
      Hint: in Xcode, do CMD+click on print, you will get the header and very interesting information related to your question. It shows why print can accept one or several parameters.
    • BananZ
      BananZ about 7 years
      Thanks guys! I am new to Swift and there is a lot more for me to learn. Any videos / tutorials / or topic that i should focus first? I have been working on Objective C for a few months.
  • greybeard
    greybeard almost 3 years
    Without an explanation how they print the same thing here, this answer is not useful.