I'm trying to find out if there is an easy way to preserve indentation of interpolated variables when using multi-line string.
Example:
let nested = """
foo
bar
"""
let nestedIndented = """
baz
qux
"""
let string = """
Hello
\(nested)
\(nestedIndented)
Bye
"""
print(string)
Expected/desired output:
Hello
foo
bar
baz
qux
Bye
Actual output:
Hello
foo
bar
baz
qux <-- qux is not indented
Bye
This can be solved by pre-indenting nested strings, before interpolating them in the final output. But this would require nested strings to be aware of the context where they would be nested, which is not desirable.
This problem is a nice example for the benefits of a custom string interpolation, thanks all. It should be noted that all solutions posted above use DefaultStringInterpolation.description to inspect the interpolated string as itβs being built up. The format of CustomStringConvertible.description is not guaranteed to be stable and we should generally try to avoid writing code that relies on a specific format.
Good suggestion, thanks. This should indeed be stable. The documentation advises against calling String.init(stringInterpolation:) directly, but it shouldn't be a problem.
extension DefaultStringInterpolation {
/// Creates a string from this instance, consuming the instance in the
/// process.
@inlinable
internal __consuming func make() -> String {
return _storage
}
}
I don't know what semantics __consuming has (or may have in the future). I'm not very familiar with the Ownership stuff yet. Does it somehow mean that you can call this only once and self becomes invalid after the call?