'SwiftUI Localize Raw Strings

In SwiftUI how can i get my raw string localized?

Text(#"Hello \\\\"#)

Adding this to the localized file will not work.

"Hello \\\\" = "is not translated \\\\";


Solution 1:[1]

"Raw strings" don't exist in the syntax of .strings files. See here:

some characters must be prefixed with a backslash before you can include them in the string. These characters include double quotation marks, the backslash character itself, and special control characters such as linefeed (\n) and carriage returns (\r).

So when you write:

"Hello \\\\" = "is not translated \\\\";

You are adding a localised string with the key Hello \\. On the other hand, your Swift string is a raw string, which means it represents the string Hello \\\\. These are different, so it is not translated.

To fix it, you should change the .strings file to escape each of the backslashes too, as it is a non-raw string:

"Hello \\\\\\\\" = "is not translated \\\\\\\\";

After that, you still need to convert the Swift raw string to a LocalizedStringKey for some reason:

Text(.init(#"Hello \\\\"#))

Note that the 8 slashes in the .strings file will become 2 slashes when displayed on the screen. This is because the 8 slashes first get reduced to 4 slashes due to the escaping syntax of the .strings file, then, since the Text.init(_:tableName:bundle:comment:) initialiser interprets the string as markdown, the 4 slashes becomes 2. Backslashes are escaped in markdown too.

Solution 2:[2]

Here is possible variant

Text(verbatim: NSLocalizedString("Hello \\\\", comment: ""))

Tested with Xcode 13.3 / iOS 15.4

Solution 3:[3]

// ...unless you explicitly convert it to a localized string key. Text(LocalizedStringKey(yourString))

Solution 4:[4]

This is possible and worked for me without add every thing anther .

"Hello \\\\" = "Hello World"

I define "Hello \\\\" as key in localized file and "Hello World" as value that .

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Asperi
Solution 3 Hammad
Solution 4 Fatemeh