String interpolation is easy in Swift. Inside a string, you can substitute in the value of a variable by placing that variable name within a \ and surrounding it by parentheses. Here is a pretty simple example of string interpolation: let color = "blue" print("The sky is \(color).")
Declaring VariablesThe var keyword is the only way to declare a variable in Swift. The most common and concise use of the var keyword is to declare a variable and assign a value to it. Remember that we don't end this line of code with a semicolon.
With the "%" operator, we can insert a variable into a string.
To declare and initialize a string variable: Type string str where str is the name of the variable to hold the string. Type ="My String" where "My String" is the string you wish to store in the string variable declared in step 1. Type ; (a semicolon) to end the statement (Figure 4.8).
In swift, string interpolation is done using \()
within strings. Like so:
let x = 10
let string = "x equals \(x) and you can also put expressions here \(5*2)"
so for your example, do:
var age:Int=1
var pet:String="dog"
lblOutput.text = "Your \(pet) is \(age) years old!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With