Heredoc-like syntax from strings in Swift

As with Objective C, there's no syntax for this in the language. Strings just have to be escaped, at the moment, at least. The alternative is to load the string from a resource file.

I'd raise a bug report with Apple on this one; it would be helpful for the language, more so than with Objective C, for just the reasons you're finding: Swift can be executed more dynamically, in a playground/REPL, so there's more reason to want to paste arbitrary stuff into string constants while you're playing.

Addendum: As an exercise in quick hacking, I just knocked up a quick and dirty Services Menu item in Automator for quoting strings in place in a playground. That's beyond the scope of this Stack Overflow answer, but I documented it on my blog.


This feature was added to Swift in 2017. (SE 0168 Multi-Line String Literals)

Swift Documentation: Welcome to Swift: Simple Values says:

Use three double quotation marks (""") for strings that take up multiple lines. Indentation at the start of each quoted line is removed, as long as it matches the indentation of the closing quotation marks. For example:

let quotation = """
I said "I have \(apples) apples."
And then I said "I have \(apples + oranges) pieces of fruit."
"""

According to a comment on Swift three double quotes, "This is brand new to Swift 4 and Xcode 9."

For more details, see Swift Documentation: Language Guide: Strings and Characters: String Literals: Multiline String Literals.


Swift doesn't support it, but C++11 does. And we can easily import it to Swift, as NSStrings.

StringConst.h:

#import <Foundation/Foundation.h>

extern NSString *const STR_PATTERN;
extern NSString *const STR_JSON;

StringConst.mm:

#import "StringConst.h"

NSString * const STR_PATTERN = @R"""((?:\["(this|is|a|pain|to|escape|properly)+)",0(?:,\[10\])?\]))""";
NSString * const STR_JSON = @R"""(window.google.ac.h(["this",[["is",0],["even",0],["worse",0]],{"q":"...","k":1}]))""";

<Target>-Bridging-Header.h:

#import "StringConst.h"

AnySwift.swift:

println(STR_PATTERN)
println(STR_JSON)

Added:

To use this in Playground, you have to create a Framework project, and Playground file in it.

sceenshot

Tags:

Swift