Skip to content

SwiftUI use of LocalizedStringKey #685

Open
@krummler

Description

@krummler

Hi there!

First off, thanks for the amazing tools you guys have created!

I'm trying to adapt SwiftGen to play nice with SwiftUI, but localisation seems to be a bit more work. I'll try to explain the situation.

SwiftUI utilises new UI components, such as Text, which takes as parameter a String or a LocalizedStringKey.

Example:

"welcome.title" = "Hey and welcome to the show!";

Can be called like:

/// Implicitly
Text("welcome.title")

/// Explicitly
Text(LocalizedStringKey("welcome.title"))

This allows the framework to automatically look up the localised string in the right language, combining this with the environment variables, allows for live debugging/testing languages. A neat example can be found in this blog post.

Like shown in the blog post, one could use a custom template to return the key wrapped in a LocalizedStringKey. But this doesn't work for parameterised translations, the LocalizedStringKey has no way to explicitly add parameters to the formatting.

To pass in parameterised strings, the key has to also contain them, example:

# Note: replacing _%lld_ with _%ld_ or _%i_ doesn't work in SwiftUI:
"nameAge %@ %lld" = "Hi there! My name is %1$@ and I'm %2$lld.";

To use this, the key has to be the interpolated string:

let name = "Dave"
let age = 42
Text("nameAge \(name) \(age)")

Swift figures out it's an interpolated string and uses that information to retrieve the right localisation.

TL;DR: currently this gets me stuck at two points:

  • %lld isn't stripped from the function name, the function name becomes nameAgeLld instead of nameAge.
  • I can't find a way to create an interpolated string in the template that SwiftUI understands.

Ideally, the generated file would return something like:

internal static func nameAge(_ p1: String, _ p2: Int) -> LocalizedStringKey {
  return LocalizedStringKey("nameAge \(p1) \(p2)")
}

Thanks so much for your help!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions