Gustavo Vollbrecht
Gustavo Vollbrecht

Reputation: 3256

Restore String Interpolation AFTER value replace

Given a str: "My name is Gustavo", that was created with "My name is \(foo.name)"

Is it possible to get the string "My name is \(foo.name)" after the value was replaced?


In other words, is it possible to find out "My name is \(foo.name)", having "My name is Gustavo"?


Edit: If I can get to "My name is ", a.k.a. the hard coded string from all strings that were build dynamically, that would be a solution.

Upvotes: 1

Views: 83

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726779

No, this is not possible. In fact, "My name is \(foo.name)" is not even included in the compiled code. Instead, Swift-5 compiler generates code equivalent to this:

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 contains details on how string interpolation is implemented in Swift-4 and Swift-5.

Upvotes: 3

Related Questions