How can you implement this multiline string literal macro in Swift?

Solution 1:

Alas Swift multiline strings are still not available, as far as I know. However when doing some research regarding this, I found a workaround which could be useful. It is a combination of these items:

  • A Quick Hack to Quote Swift Strings in a Playground - Describing how to make an service replacing and fixing texts
  • The comment by pyrtsa, regarding using "\n".join(...) to emulate the multiline strings

Setup an automated service

Using Automator you could set up an extra service with the following properties:

  • A single action of "Run Shell Script"
  • Tick off the "Output replaces selected text"
  • Change shell to /usr/bin/perl
  • Add the code excerpt below to the action window
  • Save as something like "Replace with quoted swift multiline join"

Code excerpt

print "\"\\n\".join([\n";   # Start a join operation

# For each line, reformat and print
while(<>) {
  print "    ";         # A little indentation 
  chomp;                # Loose the newline
  s/([\\\"])/\\$1/g;    # Replace \ and " with escaped variants
  print "\"$_\"";       # Add quotes around the line 

  print "," unless eof  # Add a comma, unless it is the last line
  print "\n";           # End the line, preserving original line count
 }

print "  ])"; # Close the join operation

You are of course free to use whatever shell and code you want, I chose perl as that is familiar to me, and here are some comments:

  • I used the "\n".join(...) version to create the multiline string, you could use the extension answer from Swift - Split string over multiple lines, or even the + variant, I'll leave that as an exercise for the user
  • I opted for a little indentation with spaces, and to replace the \ and " to make it a little sturdier
  • Comments are of course optional, and you could probably shorten the code somewhat. I tried to opt for clarity and readability
  • The code, as is, preserves spaces, but you could be edited if that is not wanted. Also left as an exercise for the user

Usage of service

Open up your playground or code editor, and insert/write some multline text:

  • Mark the text block
  • Execute Xcode (or similar) > Services > Replace with quoted swift multiline join

You now have a multiline string in proper swift coding. Here are an example of before and after text:

Here is my multiline text 
example with both a " and
a \ within the text

"\n".join([
    "Here is my multiline text ",
    "example with both a \" and",
    "a \\ within the text"
  ])