All,
I have created a method which takes closure like this,
extension NSManagedObject{
class func performOnWorkerContext(_ block:@escaping (_ context:NSManagedObjectContext?) -> ()){
//Create context, Call block() and save context
}
}
I use this method like this,('Request' is of type NSManagedObject). The class method will be modified to:
extension NSManagedObject{
class func performOnWorkerContext(_ block: @escaping () ->()) {
//Create context, Call block() and save context
}
}
Request.performAndWaitOnWorkerContext { context in
//Use the 'context' here
}
Now, my question is how can I use this method like this,
Request.performAndWaitOnWorkerContext {
//Use 'context' here
}
Here I want to use the variable 'context' (I dont know how to, which is the question). I have seen the similar implementation when we use setter in swift
Ex. If I use
var temp: Int {
set {
print(newValue) // Here 'newValue' is automatically available
}
get {}
}
Something like this I want to implement, please suggest if its doable or not or how setters in swift do it?
The motivation behind this is it looks more elegant and we dont have to remember obvious variables accessible in this closure.
newValue
is the default name of the parameter in the setter of
a computed property, the willSet
property observer, and the
setter of a subscript method. It is built into the language.
In a closure, you can name the parameter
Request.performAndWaitOnWorkerContext { context in
// Use `context` here
}
or use shorthand parameter names:
Request.performAndWaitOnWorkerContext {
// Use `$0` here
}
but you cannot define an implicit parameter name.