Enum with Localized String in Swift

Updated 27 August 2024

Save

Hello readers, today in our swift learning journey we will learn about how to use Enum with Localized String in Swift.

Enum with Localized String in Swift

Introduction

In Swift, an enum (short for “enumeration”) is a powerful and flexible type that represents a group of related values. In general programming terms, enumerations are used to define a common type for a group of related values.

However, with Swift, it provides variety of features and flexibility that can affect the reusability and maintainability of your code exponentially. Here in this blog, we will check how we can use Enums to localize the strings in our application.

Implementation

To integrate enum for localizing your strings in the application, you can follow the below steps.

Step 1:- Create an Enum

To create an enum in your application you do not need to import any specific framework. You can directly define the enum in your application and add some cases to it.

Step 2:- Create the Localize files

Now, create the localize (.string) files and add them to the target. Once added you must define the content within the files in key-value format. You can check the format reference below.

The value can be based on the language however the key must be the same as defined in the enum.

Step 3:- Add the Localization Function

Once you complete the above steps, you will then need to create a function that will work as a closure and will return the translated string based on the selected language.

When we add the string file and define its language code, it automatically gets wrapped inside the folder with the name as language code and extension as .lproj.

To access the file, we will need to add its path and will then need to provide the key. The function will automatically traverse the localize file and return the respective value of the keys.

Step 4:- Accessing the String

Once all the above steps are defined, you will then need to call the enum value with the enum function as an extension. Since you can declare and call the enum from anywhere, you will be able to use the translate function through the application.

Conclusion

In conclusion, we have learned how we can use Enum with Localized String in Swift to translate our texts through the application. You can learn more about the enum with the Enum documentation.

To learn more about Swift and other interesting topics, you can refer to the mobikul blogs.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home