50

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!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
carlo711
  • 645
  • 1
  • 6
  • 11
  • 1
    Your well documented answer is [here](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html#//apple_ref/doc/uid/TP40014097-CH7-ID291), in the Apple documentation. – Eric Aya Jun 05 '15 at 16:13

3 Answers3

125

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

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)
-2

example :

var age = 27
var name = "George" 

print("I'm \(name), My age is \(age)")

output: I'm George, My age is 27

you need add to back slash in front (age)

Mesut
  • 1
  • 2