在 Swift 的字符串插值中,一些特定类型的值可以接受额外的参数来定制它们的展示方式。这种机制是通过 Swift 的 String.StringInterpolation
协议实现的。在内置的类型中,Date
和 FloatingPoint
是典型的例子,它们可以接受日期格式器(DateFormatter
)和数值格式器(NumberFormatter
)作为参数。在自定义类型中,你也可以通过实现 String.StringInterpolation
协议来添加自定义的插值行为。
以下是一些示例:
对于日期:
let date = Date() let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .short print("Current date and time: \(date, formatter: formatter)")
这段代码会打印类似 "Current date and time: 6/14/23, 10:59 AM" 的结果。
对于浮点数:
let value = 1234.5678 let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .currency print("Currency formatted value: \(value as NSNumber, formatter: numberFormatter)")
这段代码会打印类似 "Currency formatted value: $1,234.57" 的结果。
对于自定义类型,你需要实现 String.StringInterpolation
协议。以下是一个例子:
struct MyType { var value: Int } extension String.StringInterpolation { mutating func appendInterpolation(_ value: MyType, radix: Int) { appendInterpolation(String(value.value, radix: radix)) } } let myValue = MyType(value: 31) print("My value in hexadecimal: \(myValue, radix: 16)")
这段代码会打印 "My value in hexadecimal: 1f"。