简体   繁体   English

这是 Swift 闭包吗?

[英]Is this a Swift closure?

I don't understand the == false part, the syntax looks like a closure but I can't find explanation in the Apple document.我不明白== false部分,语法看起来像一个闭包,但我在 Apple 文档中找不到解释。

let photoInfos = (JSON.value!.valueForKey("photos") as! [NSDictionary]).filter({
        ($0["nsfw"] as! Bool) == false
    }).map {
        PhotoInfo(id: $0["id"] as! Int, url: $0["image_url"] as! String)
    }

Is the first closure a closure?第一次关闭是关闭吗?

Yes the { ($0["nsfw"] as! Bool) == false } is a closure, it will filter the dictionary using this function (each element will take on the role of $0), if the function evaluates to true it will be kept, if not it will not.是的{ ($0["nsfw"] as! Bool) == false }是一个闭包,它将使用此函数过滤字典(每个元素将扮演 $0 的角色),如果该函数的计算结果为 true,它将被保留,如果没有它不会。

Here is a link to the doc on filter.这是过滤器文档的链接

And here are a couple more examples of closures using filter and map.这里还有几个使用 filter 和 map 的闭包示例。

// this one will filter the array by testing each element to see if the uppercased value matches the value, if so it is kept
let anArray = [ "a", "A", "b", "c"]
let aNewArray = anArray.filter { $0.uppercaseString == $0 }
print(aNewArray)  // prints the array ["A"]

// this one maps all the elements to their uppercase value    
let allUpcase = anArray.map { $0.uppercaseString }
print(allUpcase)  // "["A", "A", "B", "C"]

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

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