[swift-evolution] Proposal: Add function SequenceType.find()
Marco Masser
lists at duckcode.com
Fri Feb 19 03:21:07 CST 2016
> On 2016-02-18, at 23:13, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> wrote:
>
> 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.
If I’m not mistaken, this works OK as long as you only want to find something of a specific type. Maybe I’m missing something here, but to add some kind of predicate (e.g. checking for bitsPerPixel == 8), this would lead to code like this:
var bitmap: NSBitmapImageRep? = representations.find {
if let bitmap = $0 as? NSBitmapImageRep where bitmap.bitsPerPixel == 8 {
return bitmap
}
return nil
} ?? makeNormalizedBitmapRep()
… whereas my original version would look like this:
var bitmap = representations.find(NSBitmapImageRep.self) { $0.bitsPerPixel == 8 } ?? makeNormalizedBitmapRep()
The point of my proposed method is to filter for a *subtype* of Generator.Element and apply a given predicate only to those that match that subtype, then return the an instance of that subtype or nil.
Again, maybe I’m missing something here?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160219/daa84f25/attachment.html>
More information about the swift-evolution
mailing list