我知道我的问题标题很令人困惑,但我会让我的解释清楚。阅读我的问题后,请建议一个好的标题,以便对其他人有所帮助。
我有一个标签,其文本由 API 中的 JSON 确定。
text_from_json = "My name is _ and my age is _"
mylabel.text = text_from_json
在类中的两个常量中,我的年龄为“26”,姓名为“jack”。
let age = 26
let name = "jack"
print("mylabel.text")
//my output should be "My name is Jack and my age is 26"
我正在 Swift 中寻找类似于 Python 的函数/方法:
text_from_json = "My name is {0} and my age is {1}"
print("My name is {0} and my age is {1}".format(name, age))
Swift 中是否有类似于 Python 中的 .format
的函数?
最佳答案
在 Swift 中这非常简单。您需要执行以下操作
let name = "jacK"
let age = 26
//var formattedString = "My name is \(name) and ag is \(age)"
var formattedString = String(format: "My name is %@ and age is %d", name,age)
对于您的具体情况,您可以这样做
let name = "jacK"
let age = 26
let stringFromJSON = "My name is _ and age is _"
var formattedString = stringFromJSON.replacingOccurrences(of: "_", with: "%@")
formattedString = String(format: formattedString, name,"\(age)")
print(formattedString)
上面的代码有效。
关于swift - 如何在 Swift 中显示动态常量中的变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45250789/