2015-06-30 12 views
15

C'è un modo semplice in Swift per aggiungere virgolette a una stringa? Le virgolette devono essere localizzate correttamente (vedere https://en.wikipedia.org/wiki/Quotation_mark) in base alle impostazioni della lingua dell'utente. Mi piacerebbe mostrare la stringa in un UILabel dopo aver aggiunto le virgolette.Aggiunta di virgolette in Swift

Per esempio:

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

Per un utente francese: « essere o non essere ... »

Per un utente tedesco: „ essere o non essere. .. ”

risposta

30

Utilizzando le informazioni da 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) 

I risultati dei campioni:

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

Non so se l'inizio/chiave delimitatore finale può essere definito per un locale . In tal caso il codice sopra riportato tornerebbe alla normale double-quote ".

0
let quote = "\"To be or not to be...\"" 
println(quote) 

outp ut sarà: "Essere o non essere ..."

+0

di Apple Grazie. Sì, sembra semplice ma non localizzabile. – jerry

+0

non ho avuto si – vijeesh

+0

Si prega di consultare il link Wikipedia fornite nell'interrogazione che mostra stili virgoletta in diverse lingue. – jerry

1

Swift 4

Usando la stessa logica, ma con una sintassi semplice e moderno.

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 
    } 
} 

Quindi è possibile utilizzare semplicemente in questo modo:

print("To be or not to be...".quoted) 

Risultati

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

Inoltre, vi consiglio di leggere l'intero Internationalization and Localization Guide

Problemi correlati