Can't interpolate a Bool in SwiftUI Text?

Simple code like this gives an error.

struct MyView: View {
    @State private var test: Bool = false
    var body: some View {
          Text("Hello. \(test)")

The error:

Instance method 'appendInterpolation(_:formatter:)' requires that 'Bool' inherit from 'NSObject'

What is going on?

Answered by OOPer in 688571022

When you write a String Interpolation directly inside Text.init(_:), it is interpreted as a LocalizedStringKey, not String.

So, LocalizedStringKey.StringInterpolation works.

You should better also read this:

SE-0228 Fix ExpressibleByStringInterpolation

If you want to make a String Interpolation of String type, you can write something like this:

        Text("Hello. \(test)" as String)

Or

        Text(verbatim: "Hello. \(test)")

(In both samples, "Hello. 〜" would not be localized.)


To make it localizable, you may need to write:

        Text("Hello. \(test.description)")

Or

        Text("Hello. \(String(test))")

(To localize true or false, you may need a little more effort.)

You can write this :

        Text("Hello. \(test ? "true":"false")")

or simpler

        Text("Hello. " + String(test))
Accepted Answer

When you write a String Interpolation directly inside Text.init(_:), it is interpreted as a LocalizedStringKey, not String.

So, LocalizedStringKey.StringInterpolation works.

You should better also read this:

SE-0228 Fix ExpressibleByStringInterpolation

If you want to make a String Interpolation of String type, you can write something like this:

        Text("Hello. \(test)" as String)

Or

        Text(verbatim: "Hello. \(test)")

(In both samples, "Hello. 〜" would not be localized.)


To make it localizable, you may need to write:

        Text("Hello. \(test.description)")

Or

        Text("Hello. \(String(test))")

(To localize true or false, you may need a little more effort.)

Can't interpolate a Bool in SwiftUI Text?
 
 
Q