Search code examples
swiftstringprintingstring-formatting

Swift Print function formatting


This article has this code here:

// flatMap
let flatCars = peopleArray.flatMap({ $0.cars })
print("Flatmap: \(flatCars)")
/*Result: Flatmap: ["i20", "Swift VXI", "Crita", "Swift VXI"]*/

What is going on in the print function. Why can it not just be this:

print("Flatmap: ", flatCars) //typed outside of IDE

Is "Flatmap: \(flatCars)" meant to be string formatting similar to javascript's template literals e.g "Flatmap: ${flatCars}" in Js?

Useful resources for better understanding would be great.


Solution

  • Yes, it is similar to ${} in javaScript, and it is called String Interpolation:

    String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal.

    You can find more detailed information in here: Swift Documentation under the section "String Interpolation".