Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Quotes in Swift

Tags:

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/wiki/Quotation_mark) based on the user's language settings. I'd like to show the string in a UILabel after adding the quotes.

For instance:

var quote: String! quote = "To be or not to be..." // one or more lines of code that add localized quotation marks  

For a French user: «To be or not to be...»

For a German user: „To be or not to be...”

like image 465
jerry Avatar asked Jun 30 '15 11:06

jerry


People also ask

How do you print quotation marks in Swift?

You place your string within quotation marks ( " ) and surround that with number signs ( # ). For example, printing the string literal #"Line 1\nLine 2"# prints the line feed escape sequence ( \n ) rather than printing the string across two lines. let string = #"A string with "double quotes" in it.

How do you pass a double quote in a string?

Double Quotes inside verbatim strings can be escaped by using 2 sequential double quotes "" to represent one double quote " in the resulting string. var str = @"""I don't think so,"" he said. "; Console. WriteLine(str);

How do you escape a single quote in Swift?

Using escape character for single quotes \' = ' and interpolation ( \() )for variables you can achieve this in one string.

How do I remove double quotes from a string in swift 5?

To remove double quotes just from the beginning and end of the String, we can use a more specific regular expression: String result = input. replaceAll("^\"|\"$", ""); After executing this example, occurrences of double quotes at the beginning or at end of the String will be replaced by empty strings.


1 Answers

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

like image 106
Martin R Avatar answered Oct 05 '22 03:10

Martin R