0

All blog posts I have seen that define a DSL in Swift use trailing closures and make use of the closure parameter $0. This makes the code verbose and, I think, ugly. (For example: https://mecid.github.io/2019/01/30/creating-dsl-in-swift)

Is there a way to avoid code like this?
$0 everywhere.

let rootView = stack {
    $0.spacing = 16
    $0.axis = .vertical
    $0.isLayoutMarginsRelativeArrangement = true

    $0.label {
        $0.textAlignment = .center
        $0.textColor = .white
        $0.text = "Hello"
    }
}

Kotlin avoids this with "extension functions with receiver" (see: What does a Kotlin function signature with T.() mean?).

Is there something similar in Swift? Or is it planned?

1 Answers1

0

This is closure (anonymous function) in Swift, it helps to set functions as a variables.

Try this:

   let rootView = stack(apply: newFunction(_:))

....

 func newFunction(_ obj : UIStackView) {
        obj.spacing = 16
        obj.axis = .vertical
        obj.isLayoutMarginsRelativeArrangement = true
 }

For function:

public func stack(apply closure: (UIStackView) -> Void) -> UIStackView {
        let stack = UIStackView()
        closure(stack)
        return stack
    }
Agisight
  • 1,778
  • 1
  • 14
  • 15