简体   繁体   中英

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.

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.

Here is a link to the doc on filter.

And here are a couple more examples of closures using filter and 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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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