Search code examples
swiftstringstring-interpolation

What does backslash do in Swift?


In the following line of code, what is the backslash telling Swift to do?

print("The total cost of my meal is \(dictionary["pizza"]! + dictionary["ice cream"]!)")

Solution

  • The backslash has a few different meanings in Swift, depending on the context. In your case, it means string interpolation:

    print("The total cost of my meal is \(dictionary["pizza"]! + dictionary["ice cream"]!)")
    

    ...is the same as:

    print("The total cost of my meal is " + String(dictionary["pizza"]! + dictionary["ice cream"]!))
    

    But the first form is more readable. Another example:

    print("Hello \(person.firstName). You are \(person.age) years old")
    

    Which may print something like Hello John. You are 42 years old. Much clearer than:

    print("Hello " + person.firstName + ". You are " + String(person.age) + " years old")