Hello!
I have a quick question about Text in SwiftUI:
As described in Apple's documentation, there are two particular initializers used when passing in string literals or stored strings. I will use markdown to explain:
-
init(_ key: LocalizedStringKey, tableName: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil) is used when you pass in a string literal to Text:
Text("**Hello!**") // Localization used β
Output: Hello!
-
init<S>(_ content: S) where S : StringProtocol is used when you pass in a stored string to Text:
let content = "**Hello!**" Text(content) // Localization not used β
Output: **Hello!**
Perhaps this is a hidden detail a few people might not know about when using Text in their SwiftUI projects. If you wanted to use a stored string with localization, you could convert your string to a LocalizedStringKey and call the first initializer listed above:
let content = "**Hello!**"
Text(LocalizedStringKey(content)) // Localization used β
Output: Hello!
My question revolves around this and string interpolation. Text can take advantage of passing in different types with string interpolation, which can be really useful at times. However, when interpolating different types, I seem to have results that do not match up with my above markdown example. I will use SF Symbols to explain:
-
init(_ key: LocalizedStringKey, tableName: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil) is used when you pass in a string literal to Text:
Text("**Hello!** \(Image(systemName: "hand.wave"))") // Localization used β
Output:
-
init<S>(_ content: S) where S : StringProtocol is used when you pass in a stored string to Text:
let content = "**Hello!** \(Image(systemName: "hand.wave"))" Text(content) // Localization not used β
Output: **Hello!** Image(provider: SwiftUl.ImageProviderBox<SwiftUI.Image.NamedlmageProvider>)
Those outputs are expected. The part where I get confused is here:
let content = "**Hello!** \(Image(systemName: "hand.wave"))"
Text(LocalizedStringKey(content)) // Markdown works, but the SF Symbol does not β
Output: Hello! Image(provider: SwiftUl.ImageProviderBox<SwiftUI.Image.NamedlmageProvider>)
I am casting content to a LocalizedStringKey, but only a portion of it seems to be localized.
This isn't a difficult problem to solve. I can just use type annotation to get the desired output:
let content: LocalizedStringKey = "**Hello!** \(Image(systemName: "hand.wave"))"
Text(content) // Localization used β
Output:
However, this isn't ideal. In certain contexts, I would really like to directly cast inside the Text initializer. I have tested this with SwiftUI's Image struct using SF Symbols and images from the asset catalog, and I get the same result.
What am I misunderstanding here? What can I clarify for anyone? I really appreciate everyone's help!
Edit: I apologize if this isn't the best place to post this, but I cannot tell if this is intended behavior or not.
β Joe