[swift-users] How flatMap's signature is able to translate from Optional<Type> to [Type]?
Slava Pestov
spestov at apple.com
Mon Feb 13 19:13:17 CST 2017
> On Feb 13, 2017, at 4:40 PM, Maxim Veksler via swift-users <swift-users at swift.org> wrote:
>
> I'm trying to understand the signature of flapMap that allows it to "strip down" Optional from a type, when called on an Optional collection but remain same type when called on a non option collection.
>
> How would flatMap be implemented if would have been stand alone?
>
> This for ex. I can't get to compile:
>
> func flatMap<ElementOfResult, Element, T: Sequence>(on: T, _ transform: (Element) throws -> ElementOfResult?
> ) rethrows -> [ElementOfResult] {
> var result: [ElementOfResult] = []
> for element in on {
> if let newElement = try transform(element) {
> result.append(newElement)
> }
> }
> return result
> }
This doesn’t compile because there’s no relation between T.Element.Iterator and Element. I think you want to remove the Element type parameter altogether, and make the input type of flatMap into T.Element.Iterator.
Slava
>
>
> Additionally please see 2 related SO questions, for background.
>
> http://stackoverflow.com/q/42213656 <http://stackoverflow.com/q/42213656>
> http://stackoverflow.com/q/42214880 <http://stackoverflow.com/q/42214880>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170213/dc52d41c/attachment.html>
More information about the swift-users
mailing list