如何将变量添加到字符串中?(Swift)

Chr*_*con 19 string variables swift

我想在字符串中添加一些变量:

var age:Int
var pets:String
lblOutput.text = "Your"+ var pets +"is"+ var age +"years old!"
Run Code Online (Sandbox Code Playgroud)

这两个变量都不是零.我认为这是它在objective-c中的工作方式,不是吗?

谢谢!

小智 52

在swift中,字符串插值是在字符串内完成的\().像这样:

let x = 10
let string = "x equals \(x) and you can also put expressions here \(5*2)"
Run Code Online (Sandbox Code Playgroud)

所以对于你的例子,做:

var age:Int=1
var pet:String="dog"
lblOutput.text = "Your \(pet) is \(age) years old!"
Run Code Online (Sandbox Code Playgroud)