Many times it really pains to manage the assets and localization strings in the iOS projects, this blog is all about discussing a clean way of using them with the help of SwiftGen.
It's' a tool to auto-generate Swift code for resources of your projects, to make them type-safe to use.
They are many ways to integrate them, as usual, the simple and safe way I prefer is using cocoapods. We can simply add
pod 'SwiftGen' to our
if you are not familiar with cocoapods, I suggest you have a look here
SwiftGen isn’t really a pod, as it’s not a library your code will depend on at runtime; so the installation via CocoaPods is just a trick that installs the SwiftGen binaries in the
Pods/ folder, but you won’t see any swift files in the
Pods/SwiftGen group in your Xcode’s Pods.xcodeproj
That’s normal: the SwiftGen binary is still present in that folder in the Finder
Add a new group called
Resources and move the Assets.xcassets into the resources folder.
Move Assets.xcassets into the Resources folder
Create a new file
Colors.json to store all our colors and similarly for strings:
Localizable.strings to store all our strings
In the case of fonts, we have to maintain many font files, so it is good to create a group called Font and we can put the font file inside it.
Now create a new file
GenerateResource.sh and add the following code into it
xcassets -t swift3 "$RSROOT/Assets.xcassets" \
strings -t structured-swift4 "$RSROOT/Localizable.strings" \
colors -t swift4 "$RSROOT/Colors.json" \
fonts -t swift4 "$RSROOT/Fonts" \
xcassets -t swift4 "$RSROOT/Assets.xcassets" \
is used to provide the input file, template and output file to generate the swift code for assets, the same has been repeated for strings, fonts and colours above.
once this file is added, we need a create run script in Xcode.
Add the run script
if you are not familiar with what is a run script and how it works, please a have a look here: Run a shell script
Once we added the run script, we need to add the input and output files in it, like below:
Add few entries into the
Colors.json and localizable.strings like below:
After adding them, when you try to build the project, it will generate the output swift files like below:
copy these files into the Xcode project navigator. And lets see how we can use these in code:
That’s IT, we are done. Now
Please add your queries and valuable suggestions about the article in comments suggestion. I would like to thank Dominic Freeston who is the one made me understand the importance of clean asset management in a project!
This is a free third party commenting service we are using for you, which needs you to sign in to post a comment, but the good bit is you can stay anonymous while commenting.