57

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!

1
  • 1
    Your well documented answer is here, in the Apple documentation. Commented Jun 5, 2015 at 16:13

3 Answers 3

137

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!"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you mate for very speedy answer!
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)

Comments

0

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)

2 Comments

This solution has already been given by the accepted answer
Your suggestion is an easy to read example. For me, user user4233369 suggestion is hard to understand ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.