Strongly typed access to Info.plist file using Swift

Strongly typed access to Info.plist file using Swift

How Codable can help us to parse and access values saved in .plist by keeping them type-safe

As Apple’s developers we started facing the type-safe constraint in our code with the advent of Swift.

From my side I’ve always tried to fully embrace this approach even if often this means to come to a deal with several parts of the UIKit which are obviously created with a different — more dynamic — paradigm in mind.
Sometimes is easy, some other less, but they still a good excercise to think outside the box to keep our code safer and cleaner.

Recently I’ve re-faced an apparent trivial task; I would to read the configuration of an application saved inside the Info.plist file of the app.

My Info.plist contains an additional node called configuration with several data inside: server_url, environment_name an a bunch of other keys.

Values are dynamic and assigned based upon the current schema you have set to launch the application (ie. $(SERVER_URL) is the url server which has a value or another depending from the configuration environment like TESTING/PRODUCTION).

The goal is to get these values by keeping the type of the data.
The most straightforward approach is to use the magic behind the Codable protocol (this article is not about Codable, you can found tons of articles around like here, here or here).

The code is pretty simple, you need just specify a Codable structure which can handle your interesting data, then allocate the Plist class with the generic type.

In our example data we can provide the following structure:


You can use the class itself to read every other file other than Info.plist; just pass a .plist(“otherPListFile”) as init parameter and provide your own Codable structure.

Strongly typed access to Info.plist file using Swift was originally published in iOS App Development on Medium, where people are continuing the conversation by highlighting and responding to this story.

Powered by WPeMatico

Comments are closed.