gpt4 book ai didi

string - 在 Swift 中创建字符串模板?

转载 作者:搜寻专家 更新时间:2023-10-30 22:01:21 25 4
gpt4 key购买 nike

我想在 Swift 中将一个字符串存储为常量,这样我就可以重用它并将变量注入(inject)其中。例如,我可以在 C# 中执行此操作:

var template = "Your name is {0} and your age is {1}."
someLabel.text = string.Format(template, "John", 35)
some2Label.text = string.Format(template, "Jane", 33)

如何在 Swift 中完成此操作以便重用字符串模板?

最佳答案

使用 swift 的 printf 风格的语法来保存模板,然后像这样使用它:

var template = "Your name is %@ and your age is %d."
someLabel.text = String(format: template, "John", 35)
some2Label.text = String(format: template, "Jane", 33)

如果您以前没有使用过这种语法风格,这里有一个粗略的指南:

  • %@ :字符串(或者,正如 nhgrif 指出的那样,NSObjectdescription/descriptionWithLocale 属性>)
  • %d : 整数
  • %f : 双
  • %.2f :精度为 2 的 double ,例如2.2342 -> 2.23

Here's the documentation if you require more precision.

关于string - 在 Swift 中创建字符串模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29424637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com