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

62,330

Solution 1

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!"

Solution 2

You can add variables to a string this way also:

let args = [pets, age]

let msg = String(format: "Your %@ is %@ years old", arguments: args)

print(msg)
Share:
62,330
carlo711
Author by

carlo711

while(true){ do(); }

Updated on July 09, 2022

Comments

  • carlo711
    carlo711 almost 2 years

    I want to add some variables to a string:

    var age:Int
    var pets:String
    lblOutput.text = "Your"+ var pets +"is"+ var age +"years old!"
    

    The both variables aren't nil. And i think this is how it worked in objective-c, wasn't it?

    Thanks!

    • Eric Aya
      Eric Aya about 9 years
      Your well documented answer is here, in the Apple documentation.
  • carlo711
    carlo711 about 9 years
    Thank you mate for very speedy answer!
  • Christos Koninis
    Christos Koninis over 2 years
    This solution has already been given by the accepted answer