create a template string in swift

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.swift
let name = "John"
let age = 25
let occupation = "developer"
let greeting = "Hi, my name is \(name), I'm \(age) years old, and I'm a \(occupation)."
148 chars
5 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.swift
let pi = 3.14159265359
let formattedString = String(format: "The value of PI is %.2f", pi)
91 chars
3 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.

related categories

gistlibby LogSnag