Is there a straightforward way in Swift for adding quotation marks to a String? The quotation marks should localize properly (see https://en.wikipedia.org/w
Using the same logic, but with a modern and simple syntax.
extension String {
static var quotes: (String, String) {
guard
let bQuote = Locale.current.quotationBeginDelimiter,
let eQuote = Locale.current.quotationEndDelimiter
else { return ("\"", "\"") }
return (bQuote, eQuote)
}
var quoted: String {
let (bQuote, eQuote) = String.quotes
return bQuote + self + eQuote
}
}
Then you can use it simply like this:
print("To be or not to be...".quoted)
Results
Locale Output de „To be or not to be...“ en “To be or not to be...” fr «To be or not to be...» ja 「To be or not to be...」
Also, I advice you to read the whole Apple's Internationalization and Localization Guide
Using the information from http://nshipster.com/nslocale/:
let locale = NSLocale.currentLocale()
let qBegin = locale.objectForKey(NSLocaleQuotationBeginDelimiterKey) as? String ?? "\""
let qEnd = locale.objectForKey(NSLocaleQuotationEndDelimiterKey) as? String ?? "\""
let quote = qBegin + "To be or not to be..." + qEnd
print(quote)
Sample results:
Locale Output de „To be or not to be...“ en “To be or not to be...” fr «To be or not to be...» ja 「To be or not to be...」
I don't know if the begin/end delimiter key can be undefined for a
locale. In that case the above code would fall back to the normal
double-quote "
.
let quote = "\"To be or not to be...\""
println(quote)
output Will be: "To be or not to be..."