<div dir="ltr">Hi everyone,<div><br></div><div>I've discovered today that Swift will actually choose 2 very differently behaving types of flatMap implementation based on the input signature. </div><div><br></div><div>For a Sequence of options it will call a flatMap that filters out nil's. For a Sequence of Sequence's it will call a flattening function, without filtering.</div><div><br></div><div><font color="rgba(0, 0, 0, 0.298039)">Leading to code that (IMHO) reads very not </font><font color="#000029">inconsistency, and unexpected. Sometime even looking a bit funny such as </font><font color="rgba(0, 0, 0, 0.298039)">collection.flatMap.flatMap:</font></div><div><font color="rgba(0, 0, 0, 0.298039)"><br></font></div><div><pre style="word-wrap:break-word;white-space:pre-wrap"> 5> let deep = [["1989", nil], [nil, "Red"], [nil, nil]]
deep: [[String?]] = 3 values {
[0] = 2 values {
[0] = "1989"
[1] = nil
}
[1] = 2 values {
[0] = nil
[1] = "Red"
}
[2] = 2 values {
[0] = nil
[1] = nil
}
}
6> deep.flatMap { $0 }
$R1: [String?] = 6 values {
[0] = "1989"
[1] = nil
[2] = nil
[3] = "Red"
[4] = nil
[5] = nil
}
7> deep.flatMap { $0 }.flatMap { $0 }
$R2: [String] = 2 values {
[0] = "1989"
[1] = "Red"
}</pre>I wonder why it was implemented this way?</div><div><br></div><div><br></div></div>