Home > Blockchain >  Uncertain of this Swift struct syntax with closure
Uncertain of this Swift struct syntax with closure

Time:11-20

I'm stumped by a bit of Swift struct syntax.

For a regular struct, I understand how to define and initialize it.

struct Thing {
    let name: String
}

let aThing = Thing(name: "The Name")

But I was reading a bit about functional programming and came across this syntax and what stumped me most was the initialization.

struct Effect<T> {
    let run: (@escaping (T) -> Void) -> Void
}

// What is "callback" here? How does this work?
let anIntInTwoSeconds = Effect<Int> { callback in
    DispatchQueue.main.asyncAfter(deadline: .now()   2) {
        callback(42)
    }
}

anIntInTwoSeconds.run { theInt in
    print(theInt)
}

If I were to see that with a "normal" initializer, I would understand it, but what is happening on this line? What is this syntax called so I can research it further?

let anIntInTwoSeconds = Effect<Int> { callback in

CodePudding user response:

The declaration for the Effect type

struct Effect<T> {

Defines Effect as using a Generic type T. So you can create Effect objects that work on different types.

The line

let anIntInTwoSeconds = Effect<Int> { callback in

Creates an Effect object that operates on Ints, and assigns it to the variable anIntInTwoSeconds.

The { callback in part defines the closure for the Effect object. That declaration could be rewritten like this:

let anIntInTwoSeconds = Effect<Int>(run: { callback in
    DispatchQueue.main.asyncAfter(deadline: .now()   2) {
        callback(42)
    }
}
)

You can interpret as:

'Create an instance of the Effect struct, with a run property that contains the closure that begins with "{ callback in"...'

(It's confusing because the run property is, itself, a closure. So we create an instance of Effect, and pass it a "run" value that's a closure.)

The "callback in" part, specifically, tells the compiler that, inside that closure, the parameter to the closure should be named "callback".

  • Related