Skip to content
DeveloperMemos

Exploring LocalizedStringKey in SwiftUI

SwiftUI, LocalizedStringKey, Localization, User Interface1 min read

LocalizedStringKey is a type in SwiftUI that allows you to look up localized strings. It's commonly used for providing localized content in your app's user interface. Here are the key points about LocalizedStringKey:

  1. Implicit Localization:

    • Several SwiftUI types, such as Text, Toggle, and Picker, implicitly look up a localized string when you provide a string literal.
    • For example, when you create a Text("Hello"), SwiftUI automatically creates a LocalizedStringKey for you and uses it to look up the localized version of the "Hello" string.
  2. ExpressibleByStringLiteral:

    • LocalizedStringKey conforms to the ExpressibleByStringLiteral protocol.
    • When you use a string literal, SwiftUI creates a LocalizedStringKey instance for you, which is then used for localization.
  3. String Variables:

    • If you have a string variable (e.g., user-provided input), you can avoid localization by passing it directly to the initializer.
    • Use a string literal argument when you want localization and a string variable argument when you don't.
  4. Creating a LocalizedStringKey:

    • You can create a LocalizedStringKey explicitly using the initializer:
      1let localizedStringKey: LocalizedStringKey = "Hello"
    • If you want to localize the value of a string variable, create a new LocalizedStringKey instance from that string.
  5. Example: Suppose your app is localized into Japanese, and your Localizable.strings file contains the following translation:

    1"Today" = "今日";

    When you use a literal string like this:

    1Section(header: Text("Today")) {
    2 // ...
    3}

    SwiftUI localizes the "Today" section header. However, if you use string variables directly, they won't be localized:

    1ForEach(messageStore.today) { message in
    2 Text(message.title) // Uses the string value verbatim
    3}

Remember that LocalizedStringKey looks for a corresponding translation in your localization files. If it finds one, it replaces the key with the translated string; otherwise, it uses the key as a dummy string value.