swiftswiftuilocalizationnslocalizedstring

NSLocalizedString and value with SwiftUI


I'm trying to localize a Text view with a value inside without success!

Here's what I'm usually do:

// ContentView.swift

Text("Tomato")
/* replaced by */
Text(NSLocalizedString("text-tomato", comment: ""))

// Localizable.strings (en)

"text-tomato" = "Tomato";

But with a value inside I don't know how to proceed:

// ContentView.swift

Text("3 Tomatoes")
/* or */
Text("\(tomatoes.count) Tomatoes")
/* replaced by */
Text(NSLocalizedString("\(tomatoes.count) text-tomatoes", comment: ""))

// Localizable.strings (en)

"%@ text-tomatoes" = "%@ Tomatoes";
/* or maybe */
"(tomatoes.count) text-tomatoes" = "%@ Tomatoes";
/* or maybe */
"%@ text-tomatoes" = "(tomatoes.count) Tomatoes";

I have tried to use %@, %lld, value, etc without success. Do you have any idea?


Solution

  • I have finally found an answer right after posting my question:

    // ContentView.swift
    
    Text("3 Tomatoes")
    /* or */
    Text("\(tomatoes.count) Tomatoes")
    /* replaced by */
    Text(String(format: NSLocalizedString("%lld text-tomatoes", comment: ""), tomatoes.count))
    
    // Localizable.strings (en)
    
    "%lld text-tomatoes" = "%lld Tomatoes";
    

    It's working like a charm!

    Other example: Localization with String interpolation in SwiftUI