Swift Academy · 课时

自定义字符串插值

使用自定义片段扩展插值功能。

第 4 / 4 课13 个步骤

自定义字符串插值 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 4 节课。

自定义字符串插值

Swift 允许您通过向 String.StringInterpolation 添加方法来扩展插值的工作方式,从而为特定的参数类型或标签定制处理方式。

extension String.StringInterpolation {
    mutating func appendInterpolation(shout value: String) {
        appendLiteral(value.uppercased() + "!")
    }
}
print("Message: \(shout: "hello")")

appendInterpolation 方法

每个自定义插值都是一个 mutating func appendInterpolation(...)。它的参数决定了您在字符串括号中书写的内容。

extension String.StringInterpolation {
    mutating func appendInterpolation(repeat text: String, times: Int) {
        appendLiteral(String(repeating: text, count: times))
    }
}
print("\(repeat: "ab", times: 3)")

appendLiteral 与 appendInterpolation

在自定义方法中,您可以调用 appendLiteral 添加普通文本,并复用现有的插值来处理值,从而构建输出。

extension String.StringInterpolation {
    mutating func appendInterpolation(twice value: Int) {
        appendLiteral("\(value)\(value)")
    }
}
print("\(twice: 7)")

带标签的插值参数

第一个参数标签会成为您使用的关键字,例如 \(shout: ...)。这样可以明确表明调用位置的意图。

extension String.StringInterpolation {
    mutating func appendInterpolation(currency amount: Double) {
        appendLiteral(String(format: "$%.2f", amount))
    }
}
print("Price: \(currency: 9.5)")

多个参数

自定义插值可以接受多个参数,让您能够在传递值的同时传入选项。

extension String.StringInterpolation {
    mutating func appendInterpolation(_ value: Double, places: Int) {
        appendLiteral(String(format: "%.\(places)f", value))
    }
}
print("\(3.14159, places: 2)")

格式化值的显示方式

一个常见用途是以特定领域所需的方式呈现值,例如将数字填充到固定宽度。

extension String.StringInterpolation {
    mutating func appendInterpolation(padded value: Int, width: Int) {
        appendLiteral(String(format: "%0\(width)d", value))
    }
}
print("ID: \(padded: 42, width: 5)")

条件输出

自定义插值可以包含逻辑,根据输入生成不同的文本。

extension String.StringInterpolation {
    mutating func appendInterpolation(yesNo flag: Bool) {
        appendLiteral(flag ? "Yes" : "No")
    }
}
print("Active: \(yesNo: true)")

复用现有插值

在您的方法中,可以针对内置类型调用 appendInterpolation,在标准行为的基础上进行组合。

extension String.StringInterpolation {
    mutating func appendInterpolation(bracketed value: Int) {
        appendLiteral("[")
        appendInterpolation(value)
        appendLiteral("]")
    }
}
print("\(bracketed: 9)")

参数默认值

自定义插值可以为参数提供默认值,因此调用方可以省略这些参数。

extension String.StringInterpolation {
    mutating func appendInterpolation(money value: Double, symbol: String = "$") {
        appendLiteral(symbol + String(format: "%.2f", value))
    }
}
let sym = "EUR "
print("\(money: 5.0)")
print("\(money: 5.0, symbol: sym))")

何时使用自定义插值

当某种格式化模式在代码中反复出现时,可以考虑使用自定义插值;它会将逻辑集中起来,同时保持调用位置简洁清晰。

extension String.StringInterpolation {
    mutating func appendInterpolation(stars n: Int) {
        appendLiteral(String(repeating: "*", count: n))
    }
}
print("Rating: \(stars: 4)")

自定义插值总结

通过扩展 String.StringInterpolation,您可以将重复的格式化操作转换为可读、可复用的语法,并直接嵌入字符串中。

extension String.StringInterpolation {
    mutating func appendInterpolation(percent value: Double) {
        appendLiteral(String(format: "%.0f%%", value * 100))
    }
}
print("Done: \(percent: 0.75)")

快速检查

回想一下自定义插值背后的机制。

回顾:自定义字符串插值

您已经学会:通过使用 appendInterpolation 方法扩展 String.StringInterpolation,可以定义新的插值语法;使用 appendLiteral 和嵌套插值构建输出;还可以使用标签、多个参数和默认值,实现简洁且可复用的格式化。

extension String.StringInterpolation {
    mutating func appendInterpolation(upper value: String) {
        appendLiteral(value.uppercased())
    }
}
print("Hello \(upper: "swift")")
免费开始

用 AI 导师学习 Swift — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
122
课程
409

常见问题解答

「自定义字符串插值」课时是免费的吗?

是的 — 「自定义字符串插值」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Swift Academy 课程的其余内容,请升级到 CoddyKit PRO。 Swift Academy 课程共包含 4 节课。

「自定义字符串插值」这节课中我会学到什么?

使用自定义片段扩展插值功能。 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Swift Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Swift Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「自定义字符串插值」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Swift Academy 课中编写并运行代码吗?

能。每节 Swift Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 字符串插值基础
  2. 设置字符串中的数字格式
  3. 多行字符串字面量
  4. 自定义字符串插值
← 返回 Swift Academy