简体   繁体   中英

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 \\\\";

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

Here is possible variant

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

Tested with Xcode 13.3 / iOS 15.4

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM