Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning closure with closure parameter

Tags:

closures

swift

Suppose I have this class

class ClosureTest{
    var nestedClosure: (((String) -> Void) -> Void)?
}

How do I assign a value to nestedClosure?

I tried the code below but I'm getting an error. Can someone help explain please?

let cTest = ClosureTest()
cTest.nestedClosure = {{ myStr -> Void in } -> Void }
like image 255
meowmeowmeow Avatar asked Oct 31 '25 00:10

meowmeowmeow


2 Answers

First, typealiases will help to reduce all the paranthesis in your code:

typealias InnerClosure = ((String) -> Void)

class ClosureTest{
    var nestedClosure: ((InnerClosure) -> Void)?
}

When you want to assing a value to nestedClosure, you need to provide a closure that takes an InnerClosure as single argument and returns nothing, hence:

let cTest = ClosureTest()
cTest.nestedClosure = { (arg:InnerClosure) in
    print ("calling arg from nestedClosure:")
    arg("called from outer space") // call the inner closure
}

To use the nestedClosure, you need to provide a concrete value of type InnerClosure:

let innerClosureValue:InnerClosure = { txt in
    print ("the inner closure; txt: \(txt)")
}

cTest.nestedClosure?(innerClosureValue)

The output then is:

calling arg from nestedClosure:
the inner closure; txt: called from outer space

Alternatively, without the innerClosureValue variable:

cTest.nestedClosure?({ txt in
    print ("Or this: \(txt)")
})
like image 91
Andreas Oetjen Avatar answered Nov 01 '25 18:11

Andreas Oetjen


Dropping the Optional bit for a second, (((String) -> Void) -> Void) is:

  • A function...
    • That takes a function...
      • That takes a string
      • And returns Void
    • And returns Void

So a useful version of this would be:

{ f in f("x") }

In this, f is a (String) -> Void. It will be passed to the closure, and then the closure passed "x" to it.

For the trivial version that does nothing (like in your example), the code would be:

{ _ in }

That says "this closure takes one parameter and doesn't do anything with it."

like image 32
Rob Napier Avatar answered Nov 01 '25 20:11

Rob Napier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!