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

Maximilian Hünenberger m.huenenberger at me.com
Wed Feb 17 09:12:38 CST 2016


I think

        subviews.find{ ($0 as? NSButton)?.state == NSOnState } as? NSButton

is sufficient and makes it clear that you are searching for a specific type. Even though you have to cast twice I don't think an additional method would be worth its use since it isn't used as often.

- Maximilian

> Am 17.02.2016 um 10:32 schrieb Marco Masser via swift-evolution <swift-evolution at swift.org>:
> 
> I just saw this PR and have a quick comment about the implementation: It could be shortened by a few lines using a where clause like this:
> 
> func find(@noescape predicate: Self.Generator.Element throws -> Bool) rethrows -> Self.Generator.Element? {
>     for element in self where try predicate(element) {
>         return element
>     }
>     return nil
> }
> 
> 
> Also, I’d like suggest adding a variant that works better with heterogenous sequences, but I’ll raise that when this proposal goes into review.
> 
> FYI: That variant would look like this:
> func find<T>(_: T.Type, @noescape matching predicate: T throws -> Bool) rethrows -> T?
> 
> A question by me on the swift-users mailing list describes its intention, implementation, and usage:
> [swift-users] Which is the more idiomatic approach for pinning down	the type of a generic parameter?
> 
> Cheers,
> 
> Marco
> 
> 
>> On 2016-01-10, at 01:58, Kevin Ballard via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> Proposal PR submitted as https://github.com/apple/swift-evolution/pull/94
>>  
>> -Kevin Ballard
>>  
>>> On Tue, Dec 29, 2015, at 06:38 PM, Kevin Ballard wrote:
>>> I'm proposing a new extension method on SequenceType called find(). It's similar to CollectionType.indexOf() except it returns the element:
>>>  
>>> extensionSequenceType {
>>> /// Returns the first element where `predicate` returns `true`, or `nil`
>>> /// if such value is not found.
>>> public func find(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Self.Generator.Element? {
>>> for elt in self {
>>> if try predicate(elt) {
>>> return elt
>>>             }
>>>         }
>>> return nil
>>>     }
>>> }
>>>  
>>> -Kevin Ballard
>>  
>> 
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160217/8e45578d/attachment.html>


More information about the swift-evolution mailing list