Losiowaty
(Pawel Lopusinski)
December 21, 2022, 9:14pm
1
I've encountered quite a weird error when using string interpolation within SwiftUI.
Consider this code :
struct MyView: View {
let array: [String] = ["Hello", "World"]
var helper: String { return "\(array)" }
var body: some View {
Text("\(array)") // doesn't work
Text(helper) // works
}
}
The offending line complains that Instance method 'appendInterpolation(_:formatter:)' requires that '[String]' inherit from 'NSObject'
If I use a simple type, like Text("\(someInteger)")
then this works just fine.
I'd have expected for Text("\(array)")
to work, simply by interpolating the String first and the using the result to initialize Text
.
Does anyone know what's going on here and why string interpolation works "different" here?
tera
December 21, 2022, 9:34pm
2
This should work: Text(String("\(array)"))
The reason is – there are different initialisers at play here:
SwiftUI.Text(String("foo"))
// uses:
public init<S>(_ content: S) where S : StringProtocol
while:
SwiftUI.Text("foo")
// uses:
public init(_ key: LocalizedStringKey, tableName: String? = nil, bundle: Bundle? = nil, comment: StaticString? = nil)
where LocalizedStringKey conforms to ExpressibleByStringInterpolation
protocol.
IIUC this is done to support localisation out of the box. Somewhat non obvious but that's the way it is.
1 Like
Losiowaty
(Pawel Lopusinski)
December 22, 2022, 9:05am
3
Ok, I guess I kinda understand this.
From what I see StringProtocol
also inherits from ExpressibleByStringInterpolation
so technically both initializers "fit" here I guess.
It's just really weird that direct interpolation works for some types and doesn't work for others.