Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "{ _ in }" mean in Swift?

Tags:

swift

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
}
like image 620
Kurt1018 Avatar asked Dec 06 '22 18:12

Kurt1018


1 Answers

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.)

like image 81
Rob Napier Avatar answered Jan 05 '23 18:01

Rob Napier