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 }
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)")
})
Dropping the Optional bit for a second, (((String) -> Void) -> Void) is:
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With