2

I'm playing around with Swift and I'm having some trouble with flatMap. I've seen this StackOverflow question, which describes how to flatten an array of arrays using flatMap, but when I reproduce the same code in a playground, it does not flatten the array. I'd appreciate it if someone could provide some insight into what's going on here.

Here's a screenshot of both the code and the result:enter image description here

John
  • 143
  • 1
  • 11

1 Answers1

8

flatMap is for an array of arrays; it promotes the inner arrays' contents to be contents of the outer array. And that is all it does. It does not magically recurse. It works on an array of type [[Element]], where Element is some single type.

In other words, the flat map of [[1],[2]] is [1,2], because that is an array of arrays; its type is [[Int]].

But [1,[2]] is not an array of arrays. It isn't really an array of anything; it makes no sense in the Swift world, where an array's elements must of all be of the same type. So it is merely an array of Any (as your code acknowledges); Swift doesn't even see any arrays inside your array t1. So flatMap doesn't apply.

In an ideal world, your code wouldn't even compile, because flatMap used on an array of Any is illegal. Unfortunately there is (or used to be) another flatMap, and the compiler, having given up on the flatMap that applies to [[Element]], resorts to the other flatMap. It applies to any array, so your code ends up legal (but it still does nothing). See Flatten [Any] Array Swift.

matt
  • 515,959
  • 87
  • 875
  • 1,141