Attributed text with Text view interpolation in SwiftUI


Greetings, traveler!

Often, we need to use attributed text in our apps. SwiftUI provides several options for handling attributed text, including the AttributedString type. But did you know you can also use a Text view to create attributed text through interpolation?

This approach allows you to generate the desired attributed text declaratively. Check out the following example:

struct ContentView: View {
    
    var body: some View {        
        Text(
        """
            \(
                Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
                    .font(.headline)
                    .foregroundStyle(.blue)
            )
            \(
                Text("Integer sit amet scelerisque quam.")
                    .font(.callout)
                    .fontWeight(.black)
                    .foregroundStyle(.red)
            )
            \(
                Text("Maecenas vel erat auctor quam lobortis luctus non et tortor.")
                    .font(.title)
                    .fontWeight(.thin)
                    .foregroundStyle(.green)
            )
        """
        )
    }
}

Nice and easy!

You can also use Images with Text, like this:

Text("I")
+
Text(Image(systemName: "heart.fill"))
    .foregroundStyle(.red)
+
Text("You")

Limitations

We can only use Text view and Text modifiers that return Text view, not some View. This means we cannot write code like this, since .textCase(.lowercase) returns some View:

struct ContentView: View {
    
    var body: some View {
        Text(
        """
            \(
                Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
                    .font(.title)
                    .fontWeight(.thin)
                    .foregroundStyle(.green)
                    .textCase(.lowercase) 
            )
        """
        )
    }
}