swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.49k stars 10.35k forks source link

[SR-8437] Add filter method to Optional #50960

Open 56ed3025-6cad-4bf8-b972-9c308205a0af opened 6 years ago

56ed3025-6cad-4bf8-b972-9c308205a0af commented 6 years ago
Previous ID SR-8437
Radar None
Original Reporter @palimondo
Type New Feature
Additional Detail from JIRA | | | |------------------|-----------------| |Votes | 0 | |Component/s | Standard Library | |Labels | New Feature, LanguageFeatureRequest | |Assignee | None | |Priority | Medium | md5: 3852b2408d69c13546d326891036b911

Issue Description:

There is a strong precedent from other programming languages that have optional types to include method named filter that conditionally maps the optional to nil. The implementation is trivial:

extension Optional {
    func filter(_ predicate: (Wrapped) throws -> Bool) rethrows -> Optional {
        return try flatMap { try predicate($0) ? self : nil }
    }
}

Swift is currently missing this method. When pitched in Swift Evolution Forums, this method was met with no opposition. This looks like a clear omission without any downsides, that should be easy to add into Swift standard library without the need to go through lengthy Swift Evolution process.

belkadan commented 6 years ago

API additions always go through the Swift Evolution process.