How To Concatenate Texts In SwiftUI

Sometimes you need to concatenate texts in SwiftUI and make some part of the Text different color or style.

There is a solution to do it, use + (plus) between two or more Texts.

There is a simple Text view.

Text(“Smash Swift!”)

Let’s say you want to make the first S bold and the second one make italic. The whole post about editing styles is here.

First, split it to four Text views.

var body: some View {
    
Text(“S”)
    
Text(“mash “)
    
Text(“S”)
    
Text(“wift!”)
}

It won’t compile in Xcode 11 and in Xcode 12 there will be four Previews.

To make it working, add + between Texts.

var body: some View {
    
Text(“S”)
   
 +
    
Text(“mash “)
    
+
    
Text(“S”)
    
+
    
Text(“wift!”)
}

For now, it looks the same way as you create one Text with the whole text.

Now, add styles to the first letters.

var body: some View {
    
Text(“S”)
    
    .bold()
    
+
    
Text(“mash “)
    
+
    
Text(“S”)
    
    .italic()
    
+    
    
Text(“wift!”)
}

They’re small, to make them bigger and change their font. You can apply one .font view modifier if you embed them, for example, in VStack.

var body: some View {
    
VStack {
    
    Text(“S”)
    
        .bold()
    
    +
    
    Text(“mash “)
    
    +
    
    Text(“S”)
    
        .italic()
    
    +
    
    Text(“wift!”)
    }
    .
font(.system(size: 30))
}