[swift-evolution] Proposal: Add function SequenceType.find()

Brent Royal-Gordon brent at architechies.com
Thu Feb 18 16:13:48 CST 2016


>> I would prefer a label on the first parameter, since you're not finding the NSButton type but instead elements having the type of NSButton.
>> 
>> subviews.find(havingType: NSButton.self, matching: { $0.state == NSOnState })
> 
> To comply with the guidelines I would expect a phrase like
> 
> subviews.findElement(havingType: NSButton.self, matching: { $0.state == NSOnState })
> subviews.find(instanceOf: NSButton.self, matching: { $0.state == NSOnState })

A funny thing just happened—I was writing some Swift, needed something like `find`, remembered this thread, copied it in, andt ehn realized I wanted to find-and-cast at the same time. Here's what I ended up doing:

extension SequenceType {
    func find<U>(@noescape finder: Generator.Element throws -> U?) rethrows -> U? {
        for elem in self {
            if let returnValue = try finder(elem) {
                return returnValue
            }
        }
        return nil
    }
    
    func find(@noescape predicate: Generator.Element throws -> Bool) rethrows -> Generator.Element? {
        return try find { try predicate($0) ? $0 : nil }
    }
}

Then the code that used it ended up being:

        var bitmap = representations.find { $0 as? NSBitmapImageRep } ?? makeNormalizedBitmapRep()

Which I think is about as nice as I could've hoped for.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list