// *** before: ***
// SwiftUI already stood on builders, but the attribute was underscored and
// officially did not exist: @_functionBuilder, with no promise to keep it
// *** in version 5.4: ***
@resultBuilder
struct StringBuilder {
static func buildBlock(_ parts: String...) -> String {
parts.joined(separator: "\n")
}
static func buildOptional(_ part: String?) -> String { part ?? "" }
static func buildEither(first: String) -> String { first }
static func buildEither(second: String) -> String { second }
static func buildArray(_ parts: [String]) -> String {
parts.joined(separator: "\n")
}
}
@StringBuilder
func page(admin: Bool) -> String {
"header"
if admin {
"admin panel"
} else {
"user panel"
}
for index in 1...2 {
"line \(index)"
}
"footer"
}
print(page(admin: true))
// the builder turns the statements of the body into calls of its own
// methods - this is the whole trick behind the body of a SwiftUI view