Why does this work?

let a: EnumeratedSequence<Array<Int>> = [5, 7, 9].enumerated()
let b: Array<(Int, Int)> = Array(a)
let c: Dictionary<Int, Int> = [0: 5, 1: 7, 2: 9]
let f: (Int, Int) -> Int = { (index, value) in
    (index + 1) * value
}
let ma = a.map(f)
let mb = b.map(f)
let mc = b.map(f)

func mapAsSequence<S: Sequence>(_ x: S) -> [Int] where S.Element == (Int, Int) {
    return x.map(f)
}
let ms = mapAsSequence(a)
print(ma, mb, mc, ms)

Argument of the Sequence.map has type (Element) throws -> T. All three sequences in the example have Element as a tuple of (Int, Int), so the argument of the map should have type ((Int, Int)) -> Int, but instead it happily accepts (Int, Int) -> Int.

Is this a convenience extension in the standard library? I was not able to find it in the sources of the standard library.

We can do it as a result of an usability regression after SE-0110.

3 Likes
Terms of Service

Privacy Policy

Cookie Policy