A few days ago I cleaned up the code for my Memory game. I tried to apply two principles:

- make it readable
- make it DRY (don't repeat yourself)

I learned a lot from the experience, but there's one thing in particular I'd like to share: how to display something in a grid

1/
My Memory game displays 16 buttons: 4 rows, 4 columns. When I first wrote the app, I did exactly what you're not supposed to: I hardcoded *all* 16 buttons đŸ€Ł

2/
Super repetitive. The exact opposite of DRY. And that matters because it makes mistakes and bugs so much more likely.

3/
So how to fix it? Well, if you're doing #100DaysOfSwiftUI you might remember that ForEach allowed us to make all three flag buttons while writing the code for just one.

That's DRY, but problem: my buttons needed to be nested in 4 rows of HStacks.

4/
How do you inject that formatting? I thought about it long and hard. I finally realized I could solve this by nesting a ForEach inside a ForEach.

Damn I felt smart.

5/
But then the code wouldn't compile.

"The compiler is unable to type check this expression in a reasonable time"

6/
Well it would compile if commented out lots of stuff including my animations.

But animations make the game fun and there should be a way to make it work right?

7/
Stack Overflow was full of threads with similar Xcode compiler issues. Lots of people complaining that the Xcode compiler isn't good enough.

Maybe. But I just want my app work.

8/
After my 5th or 6th Google search a solution surfaced.

Yup, a tutorial from @twostraws 😆

https://www.hackingwithswift.com/quick-start/swiftui/how-to-position-views-in-a-grid

9/
Paul's solution is surprisingly similar to mine: it relies on a ForEach nested inside a ForEach. The key difference is that the grid is placed inside its own view.

So why does that work?

10/
Less work for us. But also apparently less work for the compiler.

So what's going on? Luckily @twostraws has another explainer that I think answers this question.

It has to do with type inference.

https://www.hackingwithswift.com/example-code/language/how-to-fix-the-error-expression-was-too-complex-to-be-solved-in-reasonable-time

12/
I think this makes sense because one of things I noticed when my project wouldn't compile is that sections of my code no longer had syntax highlighting.

13/
So is that the answer?

Breaking up your code into smaller views means:

- less work for the programmer (DRY)
- less work for the CPU in terms of type inference

I'm curious though. Are there other reasons to break up code into smaller views?

Thanks for reading.

14/ End
You can follow @TheKumano.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: