Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print in Swift 3

Tags:

printing

swift

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, ".")
like image 253
BananZ Avatar asked May 14 '17 11:05

BananZ


People also ask

How do I print a string in Swift?

You can also print entire strings. Just like variables and constants, you print a string by passing it to the print() function. Put this in your playground file and see what happens: print("I'm printing a string in Swift!")

How do I print from Xcode?

In Swift with Xcode you can use either print() or NSLog() . print() just outputs your text. Nothing more. NSLog() additionally to your text outputs time and other useful info to debug console.

What is Terminator in print Swift?

terminator. The string to print after all items have been printed. The default is a newline ( "\n" ).


2 Answers

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)")
like image 76
Bradley Mackey Avatar answered Oct 23 '22 18:10

Bradley Mackey


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!"
    
like image 36
Mr. Xcoder Avatar answered Oct 23 '22 20:10

Mr. Xcoder