Why does string localization/internationalization not work in SwiftUI

It has been proved that if a string in Text(“home) is passed as a text, it can only be interpreted as a localized keyword. If the variable is String type, it doesn’t occur. So the answer is to declare a variable of LocalizedStringKey type.

This is the unexpected code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
struct TabItem: Identifiable {
    var id = UUID()
    var name: String
    var icon: String
    var tab: TabEnum
}

var tabItems = [
	TabItem(name: "home", icon: "house", tab: .home),
]

ForEach(tabItems) { item in
	// string localizable not working in here
	// item.name is "home"
	Text(item.name)
	// but if write code like this, it's ok
	Text("home")
}

We just need to replace String to LocalizedStringKey. Then we will found the result is OK. Just like this code:

1
2
3
4
5
6
7
struct TabItem: Identifiable {
    var id = UUID()
    // declare LocalizedStringKey type will be ok~ ^_^
    var name: LocalizedStringKey
    var icon: String
    var tab: TabEnum
}
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy