I found some code when I read a book about CoreData in Swift. I am confused about the meaning of the piece of code below. What's the meaning when declaring the closure like configurationBlock: NSFetchRequest -> () = { _ in }
. especially the meaning of { _ in }.
public static func fetchInContext(context: NSManagedObjectContext, @noescape configurationBlock: NSFetchRequest -> () = { _ in }) -> [Self] {
let request = NSFetchRequest(entityName: Self.entityName)
configurationBlock(request)
guard let result = try! context.executeFetchRequest(request) as? [Self] else { fatalError("Fetched objects have wrong type") }
return result
}
This is an empty closure that takes one parameter. In its fullest form, a closure looks like:
{ parameter: Type -> ReturnType in
// Stuff it does
}
If ReturnType
is void (no return), then it can be left out. If Type
can be inferred, it can be left out. If parameter
is unused, it can be replaced with _
. And if there's no body, there's no body. So you wind up with just this when you're done:
{ _ in }
In this specific case:
configurationBlock: NSFetchRequest -> () = { _ in })
configurationBlock
is a function that takes an NSFetchRequest
and returns nothing, and its default value is a closure that does nothing. This lets you make configurationBlock
optional without having to wrap it up in an Optional
. (I go back and forth about which approach I like better, but both are fine.)
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