Swift3: enter output inside a common extension

I need to do something like this:

extension Array { 
    func flat() -> Element { return self.flatMap { $0 } }
}

But there is a problem with the type of output:

'flatMap' produces '[SegmentOfResult.Iterator.Element]', rather than the expected context type of the result element.

Edit: Usage example:

[[1,2],[3,4,5],[6]].flat()

should create [1,2,3,4,5,6]one that will be the same as:

[[1,2],[3,4,5],[6]].flatMap { $0 }
+4
source share
1 answer

If you look at the flatMap(_:)signature,

extension Sequence {
    // ...
    public func flatMap<SegmentOfResult : Sequence>(_ transform: (Self.Iterator.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Iterator.Element]
    // ...
}

, [SegmentOfResult.Iterator.Element], SegmentOfResult - , , . , Element ( ), .

, , , Element : Sequence.

, , flatMap(_:), ( , ), [Element.Iterator.Element] ( ).

extension Array where Element : Sequence {
    func flat() -> [Element.Iterator.Element] {
        return self.flatMap { $0 }
    }
}

, , Sequence:

// An extension for a sequence of sequences
extension Sequence where Iterator.Element : Sequence {

    // returns an array of the inner element type (an array of the element of the element)
    func flat() -> [Iterator.Element.Iterator.Element] { 
        return self.flatMap { $0 }
    }
}

( , , - array.flatMap{$0} !)

+4

Source: https://habr.com/ru/post/1654733/


All Articles