如何在Swift中的动态常量中显示变量值?

时间:2017-07-22 04:47:04

标签: swift variables constants

我知道我的问题标题令人困惑,但我会清楚地说明我的解释。在阅读我的问题后,请建议一个好的标题,以便它对其他人有所帮助。

我有一个标签,其文本由API中的JSON确定。

text_from_json =  "My name is _ and my age is _"
mylabel.text = text_from_json

我的年龄为#34; 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的函数吗?

1 个答案:

答案 0 :(得分:0)

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)

以上代码有效。