In Swift, we can create a template string using string interpolation. String interpolation allows us to include the values of constants, variables, expressions, or functions inside a string variable.
Here's an example:
main.swift148 chars5 lines
In the above code, we've created a string variable greeting
using string interpolation. The values of name
, age
, and occupation
are interpolated inside the string using the syntax \(value)
.
We can also use the format specifier syntax to format the values inside the string. For example:
main.swift91 chars3 lines
In the above code, we've created a formatted string variable formattedString
using the String(format: , )
initializer. The format specifier %.2f
specifies that the value of pi
should be replaced with a floating-point number with 2 decimal places.
Template strings are a powerful feature in Swift and allow us to create complex strings with dynamic values.
gistlibby LogSnag