skip to Main Content

I have the following key and its translation in String Catalog (Xcode 15.3):

enter image description here

when I put the key in a SwiftUI‘s Text like this:

let appName = "some name"
Text("login success subTitle(appName)")

it works well and returns the English translation with the argument (some name).
But what I’m trying to do is to return the English translation using a helper function to use it somewhere else other than SwiftUI‘s Text, so I’ve tried the following:

String(format: "login success subTitle%@", arguments: [appName])

but it keeps returning the key (without the argument) instead of the translation (with the argument).

Any thoughts are appreciated.

2

Answers


  1. The format parameter contains just a literal string, unlike in SwiftUI there is no implicit connection to the localized string key.

    You have to call NSLocalizedString and the simple API without arguments is sufficient.

    String(format: NSLocalizedString("login success subTitle%@", comment: ""), appName)
    
    Login or Signup to reply.
  2. The string interpolation mechanism from SwiftUI’s Text view works with String(localized:) as well:

    let appName = "some name"
    let welcome = String(localized: "login success subTitle(appName)")
    print(welcome)
    // You have successfully logged in. Welcome to some name.
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search