【问题标题】:How can I add Variables into a String?(Swift)如何将变量添加到字符串中?(Swift)
【发布时间】:2015-08-20 16:01:48
【问题描述】:

我想给一个字符串添加一些变量:

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

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

谢谢!

【问题讨论】:

  • 在 Apple 文档中,您有据可查的答案是 here

标签: string swift variables


【解决方案1】:

示例:

var 年龄 = 27

print("我(年龄)岁。")

输出:我今年 27 岁。

你需要在前面添加反斜杠(年龄)

【讨论】:

  • 这个解决方案已经被接受的答案给出了
【解决方案2】:

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

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

所以对于你的例子,做:

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

【讨论】:

  • 谢谢你的朋友非常迅速的答复!
猜你喜欢
  • 2023-03-12
  • 2015-11-14
  • 2012-02-23
  • 1970-01-01
  • 2017-09-09
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 2021-12-21
相关资源
最近更新 更多