SwiftUI中带复数形式的本地化实现及配置失效问题排查
Hey, I see exactly where the problem is here!
The core issue is that your current Text("payment \(name) \(amount)") code just creates a regular string via interpolation—it doesn't tell SwiftUI to use your localized formatting rules from the Localizable.stringsdict. The system can't automatically map that interpolated string to the key in your stringsdict file.
Fixing the Code
You need to use Apple's official localization formatting APIs to make this work. Replace your Text view with this code:
struct ContentView: View { let name = "Erwin" let amount = 1 var body: some View { Text(String.localizedStringWithFormat( NSLocalizedString("payment %@ %d", comment: "Payment message showing who gets how much"), name, amount )) } }
Here's what this does:
NSLocalizedStringfetches the base format string from your stringsdict using the key"payment %@ %d"localizedStringWithFormatfills in the placeholders (nameandamount) and applies the pluralization rules defined in your stringsdict
Quick Checks to Ensure Everything Works
Double these settings to avoid other common pitfalls:
- Target Membership: In Xcode, select your
Localizable.stringsdictfile, then check the right sidebar—make sure your app's target is checked under "Target Membership" - Localization Setup: Go to your project's Info tab, scroll to "Localizations", and confirm you've added your target language (e.g., English) and that the stringsdict is included for that language
- Device Language: Make sure your simulator/phone is set to the language you're testing (the one you configured the stringsdict for)
Once you make these changes, your app should correctly display Erwin gets 1 euro. when amount is 1, and handle plural forms like Erwin gets 5 euros. automatically!
内容的提问来源于stack exchange,提问作者Kristof Nijs

