Does Swift has a string builder class?

In other languages, I usually have a StringBuilder class that provides the functionality to concatenate strings in an efficient way.

// pseudo code
let sb = StringBuilder()
sb.append("text")
sb.appendFormat("name=%@", name)

I am aware of @resultBuilder, but does Swift provide a builtin construct?

Answered by Claude31 in 762776022

It is builin in Swift:

var sb = "" // equivalent to StringBuilder()
let name = "imneo"
sb += "text, " // or sb.append("text")
sb.append(String(format: "name=%@", name))  // sb.appendFormat("name=%@", name)
print("string:", sb)

you get

string: text, name=imneo
Accepted Answer

It is builin in Swift:

var sb = "" // equivalent to StringBuilder()
let name = "imneo"
sb += "text, " // or sb.append("text")
sb.append(String(format: "name=%@", name))  // sb.appendFormat("name=%@", name)
print("string:", sb)

you get

string: text, name=imneo

There's also string interpolation(https://docs.swift.org/swift-book/documentation/the-swift-programming-language/stringsandcharacters/), so you could do something like this:

let sb = "text name=\(name)"

You can insert other types, too, and there are formatting options for the interpolated values.

Does Swift has a string builder class?
 
 
Q