如何将变量添加到字符串中?(Swift) [英] How can I add Variables into a String?(Swift)

查看:37
本文介绍了如何将变量添加到字符串中?(Swift)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

谢谢!

推荐答案

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

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

这篇关于如何将变量添加到字符串中?(Swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆