Adding Quotes in Swift

后端 未结 3 627
情深已故
情深已故 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

提交回复
热议问题