For case vs compactMap + forEach


Me and a friend were discussing the differences between

for case let button as UIButton in subviews {
  // do something with the button


subviews.lazy.compactMap { $0 as? UIButton }.forEach {
  // Do something with the button

at the level of the generated binary code.

Also, what if lazy is omitted?

I know that, generally speaking, without lazy, compactMap will generate intermediate array, then call forEach on the items of this new array.

My questions are:

  1. Does the compiler manage to figure out that those intermediate arrays are not used and produce code without them?
  2. In the lazy case is there any difference in the generated code between for case and lazy.compactMap{}.forEach{}?

Can I get some pointers as to how I can explore the generated code, both the intermediate representation and the optimized binary?

Apart from that, it would be nice if we can hear from someone on the @core-team who can shed some light on how those two constructs defer when generating SIL.

Thanks. is a very useful tool for this.

Terms of Service

Privacy Policy

Cookie Policy