How flatMap's signature is able to translate from Optional<Type> to [Type]?

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

}

Additionally please see 2 related SO questions, for background.

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

···

On Feb 13, 2017, at 4:40 PM, Maxim Veksler via swift-users <swift-users@swift.org> wrote:

Additionally please see 2 related SO questions, for background.

swift - How flatMap API contract transforms Optional input to Non Optional result? - Stack Overflow
swift - flatMap does not filter out nil when ElementOfResult is inferred to be Optional - Stack Overflow
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users