Search code examples
iosswiftstring-catalog

Swift: Getting localized string with an argument from String Catalog


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.


Solution

  • 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.