Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raw Strings in Swift

Tags:

string

swift

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.

like image 963
penland365 Avatar asked Jun 11 '14 15:06

penland365


3 Answers

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]+"#
like image 174
shakil080 Avatar answered Nov 15 '22 07:11

shakil080


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”.

like image 23
bjornte Avatar answered Nov 15 '22 07:11

bjornte


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.

like image 34
Anton Avatar answered Nov 15 '22 09:11

Anton