I am sure the answer is no, but is it possible to add comments to multi-line string literals that don't get included in the String? I recently had a need for something like this in a (much larger) JSON literal:

"""
{
  "someFlag" : true,
  "someOtherFlag" : "true" // <== Yes that really is meant to be a string. Stupid server.
}
"""

After posting that I came up with a workable, but slightly inelegant solution:

@inlinable
@inline(__always)
func comment(_: Any) -> String {""}

let JSON =
"""
{
  "someFlag" : true,
  "someOtherFlag" : "true" \(comment("Yes that really is meant to be a string. Stupid server."))
}
"""

Any better ways?

You can (ab)use string interpolation for that

extension DefaultStringInterpolation {
    func appendInterpolation(comment _: String) { }
}

let test = """
    this is a first line
    this is a line with a comment \(comment: "Hello! I am a comment!")
    this is a third line
    """
3 Likes

Thanks - Similar to mine but slightly neater with one less level of brackets.

Note, in both the original aspiration and the interpolation workaround, there is a probably unintentional extra space after "true".

Indeed - That was more for clarity. In my case that extra space will be happily swallowed up by the JSON parser, but worth remembering for less structured text.