Heredoc-like string syntax in Swift

Is there an alternative syntax for strings in Swift? I need to copy / paste blocks of text, including many quotes, and exit from them every time, this is a pain.

I am looking for something like PHP heredoc syntax or triple-quoted Python strings. Similar to this question , but I don't need newlines, I just need to ignore quotes and backslashes.

Here is a concrete example of the disaster I'm facing right now:

let pattern = "(?:\["(this|is|a|pain|to|escape|properly)+)",0(?:,\[10\])?\])" // that makes me sad let json = "window.google.ac.h(["this",[["is",0],["even",0],["worse",0]],{"q":"...","k":1}])" // that makes me cry 

Thanks.

+6
source share
3 answers

Like Objective-C, there is no syntax in this language in this language . The strings just have to escape, for the moment, at least. An alternative is to load a line from a resource file.

I would raise an error report with Apple about this; this would be useful for the language, to a greater extent than for Objective-C, only for the reasons you find: Swift can execute more dynamically on the playground / REPL, so there are more reasons to insert arbitrary material into string constants while you are playing.

Addendum: As an exercise in quick hacking, I simply tapped the quick and dirty menu item "Tools" in "Automator" to quote lines on the playground. This is beyond the scope of this stack overflow answer, but I posted it on my blog .

+6
source

Swift does not support it, but C ++ 11 does . And we can easily import it into Swift, like NSString s.

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 a Playground, you need to create a Framework project and a Playground file.

sceenshot

+3
source

This feature was added to Swift in 2017. ( SE 0168 Multiline String Literals )

Swift Documentation: Welcome to Swift: Simple Values says:

Use three double quotation marks ( """ ) for lines spanning multiple lines. Indents at the beginning of each line in quotation marks are removed if they coincide with the indentation of closing quotes. 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, there are three double quotes : "This is brand new for Swift 4 and Xcode 9."

For more information, see the Swift Documentation: Language Guide: strings and characters: string literals: multi-line string literals .

0
source

Source: https://habr.com/ru/post/1208766/


All Articles