How to concatenate String respecting RTL/LTR

Viewed 417

When concatenating strings, how can I make Swift respect locale right-to-left language settings?

import Foundation

var leftString = "1"
let rightString = "2"

let concatString1 = "\(leftString)\(rightString)" // 12
let concatString2 = leftString + rightString // 12
let concatString3 = String(format: "%@%@", leftString, rightString) // 12
let concatString4 = [leftString, rightString].joined(separator: "") // 12
let concatString5 = leftString.appending(rightString) // 12

How could I get 21 for RTL languages and 12 for LTR languages, depending on the locale setting of the users device?

Is the only way specifying a format like "%2$@%1$@" in a strings file?

1 Answers

You can create a function or extension for it. I have used a function in my previous project. You can check if that work for you.

func getDirectionalString(leftString : String, rightString: String) -> String
{
    if(UIApplication.shared.userInterfaceLayoutDirection == UIUserInterfaceLayoutDirection.rightToLeft)
    {
        //RTL
        return "\(rightString)\(leftString)"
    }
    return "\(leftString)\(rightString)"
}
Related