How do I add variables to a string? (Swift)

I want to add some variables to the line:

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

      

Both variables are nonzero. And I think this is how it works in objective-c, right?

Thank!

+3


source to share


1 answer


In quick succession, string interpolation is done using \()

within strings. For example:

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

      

+18


source







All Articles