I’m currently building an app that is going to have Localization. This is a new topic for me and I’m struggling to find an efficient way of handling it. Typically we’d put our strings in Localizable.strings and then anywhere we need to use them we’d use something like NSLocalized("someKey", comment: "")
however I feel like there’s a much better way to do this and to keep them organized, I just don’t know what that method is yet. Here’s what I’ve done so far.
Localizable.strings
"someKey1" = "Hello World";
"someKey2" = "Hello StackOverflow";
StringConstants.swift
enum AlertStrings {
case ok
case cancel
}
enum HelloStrings {
case world
case stackOverflow
func getString() -> String {
var stringValue = ""
switch self {
case .world
stringValue = "someKey1"
case .stackOverflow:
stringValue = "someKey2"
}
return NSLocalizedString(stringValue, comment: "")
}
Now with this type of setup, I can simply get my strings, without having to remember keys, by doing HelloStrings.world.getString()
or HelloStrings.stackOverflow.getString()
. This works, however, there’s quite a bit of setup that goes into this for each and every string value that I use. Is there a better way? I’d love to be able to just use something like HelloStrings.world
but I suspect that’s not possible.
2
Answers
For iOS you would like to use a default
.strings
files withNSLocalizedString
macro.Here is a full tutorial:
https://lokalise.com/blog/getting-started-with-ios-localization/
HelloStrings.stackOverflow.localized
If you use SwiftUI :
Text(HelloStrings.world.localized)