简体   繁体   English

Swift中“{_ in}”是什么意思?

[英]What does “{ _ in }” mean in Swift?

I found some code when I read a book about CoreData in Swift. 当我在Swift中读到一本关于CoreData的书时,我发现了一些代码。 I am confused about the meaning of the piece of code below. 我对下面这段代码的含义感到困惑。 What's the meaning when declaring the closure like configurationBlock: NSFetchRequest -> () = { _ in } . 声明闭包时的含义是什么,如configurationBlock: NSFetchRequest -> () = { _ in } especially the meaning of { _ in }. 特别是{_ 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. 如果ReturnType为void(无返回),则可以省略它。 If Type can be inferred, it can be left out. 如果可以推断出Type ,则可以省略它。 If parameter is unused, it can be replaced with _ . 如果parameter未使用,则可以用_替换。 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. configurationBlock是一个接受NSFetchRequest并且不返回任何内容的函数,它的默认值是一个什么都不做的闭包。 This lets you make configurationBlock optional without having to wrap it up in an Optional . 这使您可以将configurationBlock可选,而无需将其包装在Optional (I go back and forth about which approach I like better, but both are fine.) (我来回讨论哪种方法我更喜欢,但两者都很好。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM