值替换后恢复字符串插值

Restore String Interpolation AFTER value replace

给定一个字符串:"My name is Gustavo",它是用 "My name is \(foo.name)"

创建的

是否可以得到替换值后的字符串"My name is \(foo.name)"


也就是说,是否可以找出"My name is \(foo.name)",有"My name is Gustavo"


编辑:如果我能到达"My name is ",a.k.a。来自动态构建的所有字符串的硬编码字符串,这将是一个解决方案。

不,这是不可能的。事实上,"My name is \(foo.name)" 甚至没有包含在编译代码中。相反,Swift-5 编译器生成的代码等效于此:

let str = String(stringInterpolation: {
    var temp = String.StringInterpolation(literalCapacity: 11, interpolationCount: 1)
    temp.appendLiteral("My name is ")
    temp.appendInterpolation(foo.name)
    return temp
}())

This article 包含有关如何在 Swift-4 和 Swift-5.

中实现字符串插值的详细信息