swiftuilocalizedstringkey

How to use a string variable with LocalizedStringKey


I'm stuck when trying to use a variable to define a LocalizedStringKey. For example, in the simplified code below, Option 1 returns the translated value from my localizable.strings file but I'm trying to get Option 2 to work. The returned error is "The compiler is unable to type-check this expression in reasonable time....".

var body: some View {
        ForEach(Array(stride(from: 0, to: 2, by: 1)), id: \.self) { index_v in
            let sPartList: [String] = ["ST", "MT", "LT"]
            let test: LocalizedStringKey = "ST"  // Option 1 works
            // let test: LocalizedStringKey = sPartList[0]  //Option 2 doesnt work
            
            HStack(alignment: .top) {
                Text("Hello")
                Text(test)
              }
         }
}```


Solution

  • First of all consider that from: 0, to: 2 returns the numbers 0 and 1, if you want 0, 1 and 2 you have to use through

    To make the second option work just create an LocalizedStringKey explicitly and use the index variable rather than a fixed literal.

    ForEach(Array(stride(from: 0, through: 2, by: 1)), id: \.self) { index in
       let test = LocalizedStringKey(sPartList[index])
       ...
    

    Annotate types only if the compiler cannot infer them.