Hi all,
Got a bit confused by all the entries on this topic. my two cents then:
I do prefer the simple solution that is available in C# to obtain a verbatim (raw) string from a literal.
(I wonder why this hasn't been already implemented in Swift at the start of its existence.)
In C# one would use:
str = @"\nfoo\nfoo\tab" // C# code
This would assign literal string to str as wysiwyg.
For the time being, for those who cannot wait for a swift builtin implementation:
I took the liberty to implement this as a nifty Swift String Extension, like so:
// Created by Ted van Gaalen on 27.06.18.
import Foundation
prefix operator | // just a vertical bar as @ is not available for a custom operator.
// Use this "|" op in front of a string literal to get it verbatim (raw)
// like so:
let str = |"\nfoo\nfoo\rfoo\tfoo" //which evaluates wysiwyg.
extension String
{
static prefix func | (s: String) -> String
{ // escape char dictionary: customize/ correct if necessary:
var escap: [Character:String] =
["\0" : "\\0",
"\\" : "\\\\",
"\t" : "\\t",
"\n" : "\\n",
"\r" : "\\r" ]
var result = ""
s.forEach{ result += escap[$0] ?? String($0)}
return result
}
}
Please note that this raw string operator function has been only marginally tested,
because playground in my XCode Version 9.4.1 (9F2000) doesn't work
as it also didn't in previous XCode versions. It tells me that it is running
and it would probably run forever. Maybe it is looking for 42.
Someday they might get it working again, I hope.
The above extension might be not very efficient, but because its deployment
only make sense with string literals, this is probably of less importance.
Oh, and please don't tell me that I am deploying FP here :o)
Note, that a lot of "missing" language features and other whistles and bells
can be implemented quite easily as Swift Extensions, now, ain't that cool?
Kind regards
TedvG