Master String Interpolation in SwiftUI Localization
Written by Team Kodeco
When dealing with localization in SwiftUI, understanding how string interpolation works is crucial. These specifiers allow you to insert variables into your strings dynamically, adapting to the different types of data your app may need to display. This chapter will dive deeper into string interpolation specifiers and provide a working example to illustrate their use.
String interpolation is a powerful feature in Swift, allowing you to construct a new String
value from a mix of constants, variables, literals and expressions. When localizing your app, you’ll often use string interpolation to construct sentences or phrases dynamically.
However, it’s important to note that when Xcode parses Text
views using interpolated strings for localization, it defaults to using %@
as the specifier, which may not be suitable for all types of values.
To follow along with this example, add a Localizable.strings file to your project and add Arabic as a new language. See the chapter “Create a Localized String in SwiftUI” for detailed instructions.
Here’s how you can specify the correct interpolation specifier:
struct ContentView: View {
@State private var numFiles = 64
var body: some View {
VStack {
Text("Copying \(numFiles, specifier: "%d") files",
comment: "File copy message that indicates the number of files copied by the operation")
}
}
}
You’ll need to add the localizations to your Localization.strings files. Add the following to your English translation:
"Copying %d files" = "Copying %d files";
And then the following to your Arabic translation:
"Copying %d files" = "جاري نسخ %d ملفات";
Edit the current scheme to set the App Language to Arabic and the App Region to an Arabic-speaking region, such as United Arab Emirates. Then, run the simulator to see the following:
In this example, you use %d
as the specifier for the integer numFiles
in your string interpolation. This specifier is suitable for integer values, while %f
is suitable for floating-point values, and %@
is a general-purpose specifier suitable for many Swift types.
Translators can then substitute the %d
placeholder with the appropriate translation, maintaining the dynamic nature of the original string.
Understanding and using string interpolation specifiers correctly is a crucial aspect of SwiftUI localization, ensuring that your app’s dynamically constructed strings translate correctly into different languages.