Adding Quotes in Swift

后端 未结 3 599
情深已故
情深已故 2021-01-07 19:02

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

相关标签:
3条回答
  • 2021-01-07 19:27

    Swift 4

    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

    0 讨论(0)
  • 2021-01-07 19:37

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

    0 讨论(0)
  • 2021-01-07 19:38
    let quote = "\"To be or not to be...\""
    println(quote)
    

    output Will be: "To be or not to be..."

    0 讨论(0)
提交回复
热议问题