Hello Function Builders

This is an introductory post to functionBuilders. I will dive deeper into functionBuilders in another post

Ever wondered how SwiftUI syntax works

let view = VStack {
    Text("Hello")
}

This is powered by a new Swit Evolution Proposal SE-0289 called Function Builders And it is available for us since Swift 5.1 Function Builders are essentially syntax sugar, that let a programmer write DSL like code.

Here, I want to demonstrate how to create a simple Function Builder. So you can get your head around, instead of reading through the lengthy and bit hard to chew proposal.

We will create a SentenceBuilder. Which as you can imagine, a functionBuilder that creates a sentence out of a set of words.

@_functionBuilder
struct SentenceBuilder {
    static func buildBlock(_ items: String...) -> String {
        var myString = ""
        items.forEach { myString.append(" \($0)") }
        return myString
    }
}

Consider SentenceBuilder as a closure/type. Now you need a function that make use of SentenceBuilder.

func Sentence(@SentenceBuilder _ content: () -> String) -> String {
    return content()
}

Now you have your own SwiftUI like syntax. That takes in words and gives back a sentence

let mySentence = Sentence {
    "Hello"
    "foo"
    "bar"
}
print(mySentence)

This post intends only to be a starter material to demo how functionBuilders work. I will do a deep dive into these in a later post.