String interpolation of Bool

Often when debugging a SwiftUI app I want to do something like this:

Text("myBool = \(myBool)")

But the compiler doesn't like that, so I have to do this instead which is tedious:

Text("myBool = \(String(describing: myBool))")

Is there a particular reason why String interpolation cannot handle a Bool value or why the Swift compiler shouldn't be changed to handle this?

1 Like

This might have something to do with SwiftUI itself; the compiler is happy with the following code (in Xcode Version 13.4 (13F17a))

@main
struct BoolString {
    struct Text {
        let value : String
        init (_ value : String) {
            self.value = value
        }
    }
    static func main () {
        let foo = true
        print (true, "\(true)", Text ("foo = \(foo)"))
    }
}

@ibex10 You're correct, this is a SwiftUI thing.

Localizing strings

If you initialize a text view with a string literal, the view uses the init(_:tableName:bundle:comment:) initializer, which interprets the string as a localization key and searches for the key in the table you specify, or in the default table if you don’t specify one.

The first parameter of that initializer is a LocalizedStringKey, and not just a plain String. It implements ExpressibleByStringInterpolation in its own way, which allows you to use Formatters in the string interpolation segments for numbers, dates, etc.

1 Like

To address the issue OP is having:

You either need to handle the boolean yourself in the way that make the resulting string into a valid localized string key, or...

If you don't want to localize this String, or you want to do it yourself, you should use Text.init(verbatim:) instead.

3 Likes