UTM icon indicating copy to clipboard operation
UTM copied to clipboard

Fix improper string formatting

Open MMP0 opened this issue 3 years ago • 0 comments

Some changes to make it more localization-friendly.


Examples:

NSLocalizedString and interpolation

In SwiftUI, \( ) interpolation in LocalizedStringKey is automatically formatted with localized formatting-text, but for String it just concatenates strings.

NSLocalizedString("\(sizeString) Drive", comment: "")

This means trying to reference localized strings like: “6 GB Drive”, “32 GB Drive”, “50 GB Drive”, …

Solution

String.localizedStringWithFormat(NSLocalizedString("%@ Drive", comment: ""), sizeString)

Nil-coalescing operator in Text

Text(someObj.optionalString ?? "Empty")

This gives the same result as Text(verbatim: someObj.optionalString ?? "Empty"); “Empty” is also String and is not localized.

Solution

if let str = someObj.optionalString {
	Text(str) // <- String
} else {
	Text("Empty") // <- LocalizedStringKey
}
// or
someObj.optionalString.map { Text($0) } ?? Text("Empty")

LocalizedStringKey cannot be nested with \( ) interpolation

Text("Hello, \("world")!")

“world” is String and is not localized.

Solution

Text("Hello, \(Text("world"))!")

MMP0 avatar Aug 08 '22 12:08 MMP0