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

标签 swift variables constants

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

我有一个标签,其文本由 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/

相关文章:

ios - UIView 捕获单指 Action ,但发送两指捏合以查看后面

python - 即使 DAG 未运行, Airflow 变量也会更新

php - libxml 常量是可访问的,但不要注册为定义的常量

swift - 自定义类中的选择器

swift - #file 是否被视为 Swift 中的文字字符串?

iOS 8 从 PHAsset 快速加载图像

c++ - 添加公共(public)变量时崩溃

linux - ssh-keygen 接受标准输入

C++ const-ness,Boost 无序映射,operator[]

c++ - 在 C++ 中拆分 const char*