In this article we can see how we can statically reference strings.
Let’s look on the following example:
1 2 3 4 5 6 7 8 9 10 11 |
struct ContentView: View { var body: some View { HStack { Text("Hello, world!") Spacer() Text("Today is a sunny day") } .padding() } } |
As we described in the http://trikalabs.com/project-mess-1-no-localised-strings/ article we can use localised files so we can have all the user facing strings in one place and also to support localisation easier.
Let’s crate in a similar way our localised file:
Now we can use them in our view:
1 2 3 4 5 6 7 8 9 10 |
struct ContentView: View { var body: some View { HStack { Text(NSLocalizedString("WELCOME_GREETING", comment: "")) Spacer() Text(NSLocalizedString("WELCOME_WEATHER_UPDATE_TEXT", comment: "")) } .padding() } } |
But there are still error prone since we have to hardcode the key.
Let’s now see how we can use the SwiftGen to enable us to statically reference the strings.
- Install SwiftGen. In this article we will do it through homebrew
1brew install swiftgen - Next create a yml file for the configuration
123456789strings:inputs:- Accessible/Localizable.stringsoutputs:- templateName: structured-swift5params:publicAccess: trueenumName: Stringsoutput: Accessible/Strings+Generated.swift - Drag the file into Xcode, but don’t add in any target.
- Now we can add a run script in the build phases
12345if which swiftgen >/dev/null; thenswiftgenelseecho "warning: SwiftGen not installed, download it from https://github.com/SwiftGen/SwiftGen"fi - By building the project we can see the autogenerated file
- Lets add it to the main target, and let’s open it
- And we can now use it to statically refer to our strings
12345678910struct ContentView: View {var body: some View {HStack {Text(Strings.welcomeGreeting)Spacer()Text(Strings.welcomeWeatherUpdateText)}.padding()}}
SwiftGen allow us to create and use our own templates. We will explore this option in another article.
Resources:
https://github.com/SwiftGen/SwiftGen
https://www.raywenderlich.com/23709326-swiftgen-tutorial-for-ios