Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add Variables into a String?(Swift)

People also ask

How do you add a variable to a string in Swift?

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).")

How do you add a variable in Swift?

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.

Can you put a variable in a string?

With the "%" operator, we can insert a variable into a string.

How do you declare a variable in 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!"