[swift-evolution] [Accepted and Focused Re-review] SE-0187: Introduce Sequence.filterMap(_:)

Brent Royal-Gordon brent at architechies.com
Thu Nov 16 04:06:23 CST 2017


> On Nov 15, 2017, at 4:36 PM, Greg Parker via swift-evolution <swift-evolution at swift.org> wrote:
> 
> "compactMap" is okay if "compact" is added. Is "compact" a common enough operation in practice to pull its own weight?

Lines containing code like `flatMap { $0 }`—which could be compacting optionals or flattening nested sequences—appear 89 times in the source compatibility suite. (I happen to have it on my hard drive right now.)

My main concern about adding a compacting method is…well, am I missing a better implementation than the slightly gross one I cooked up in a playground just now?

	protocol _OptionalProtocol {
	    associatedtype _Wrapped
	    var _optional: _Wrapped? { get }
	}
	
	extension Optional: _OptionalProtocol {
	    var _optional: Wrapped? {
	        return self
	    }
	}
	
	extension Sequence where Element: _OptionalProtocol {
	    func compacted() -> [Element._Wrapped] {
	        return flatMap { $0._optional }
	    }
	}
	
	let a = [1, nil, 2]
	a.compacted()           // [1, 2]


-- 
Brent Royal-Gordon
Architechies

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20171116/e601020d/attachment.html>


More information about the swift-evolution mailing list