Is there a functional equivalent in Swift to Scala's Raw String or the verbatim string literal in C#?
Sample raw string without escape characters (not syntactically correct):
val secretKey = """long\^578arandom&61~8791escaped&*^%@(chars"""
I've tried briefly gripping through the language docs but haven't found a functional equivalent yet.
Swift 5 supports raw strings now. With this feature, backslashes and quote marks are interpreted as to their respective literal symbols. They are not treated as escapes characters or string terminators in raw strings.
To use raw strings, # symbol is used(same as python uses ‘r’ or ‘R’). Here are the number of variations for using raw strings in swift 5:
let myPets = #"The name of my dog is "barky" and my cat is "smily"."#
//The name of my dog is "barky" and my cat is "smily".
Inside of the raw string # is used for string interpolation instead of usual backslash of swift.
let val = 1
let result = #"The answer is \#(val)."#
//The answer is 1
If you want to use # inside of a raw string, place ## at the beginning and at the end.
let str = ##"I am happy bla#blablabla"##
//"I am happy bla#blablabla"
Raw strings will be helpful for regular expressions I guess, lesser backslashes in regex definition. For example:
let regex_Prev = "\\\\[A-Z]+[A-Za-z]+\\.[a-z]+"
Now we can write:
let regex_Swift5version = #"\\[A-Z]+[A-Za-z]+\.[a-z]+"#
Supposedly, this is implemented in Swift 5, see SE-0200 – Support Raw Text. From the document:
You may pad a string literal with one or more #
characters:
#"She said, "This is dialog!""#
// Equivalent to "She said, \"This is dialog!\""
#"A \"quote"."#
// Backslash interpreted as an extra character.
Currently expected Swift 5 release date: “Early 2019”.
There is currently no such function, swift is new. In the conference speakers encouraged us to report anything that you feel swift needs. Therefore I suggest you to report that you need a raw string function like Scala.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With