SwiftUI Fundamentals, Episode 9: Challenge: Stacks & ForEach | raywenderlich.com

Test your understanding of layout with stacks, and your command of ForEach, in this hands-on challenge.

This is a companion discussion topic for the original entry at https://www.raywenderlich.com/28684524-swiftui-fundamentals/lessons/9

Hi can we also accomplish this challenge using functions instead of struct views?
(writing reusable functions)
I wanna understand why we have to use struct views if we can achieve the same using functions?
Apologies ahead if my question seems to be not reasonable coming from javascript background self upskilling to swift ui there is a massive language culture difference

Hi! Thanks for your question.

I don’t have much experience with javascript, so I’m not sure what you mean. And maybe it is just like you say a big difference in language! Structs + the View protocol are the base level building block of SwiftUI, so you can’t really avoid them.

Since you’re already experienced in another area, this article focused on reusable SwiftUI Views might help you: ViewBuilder Tutorial: Creating Reusable SwiftUI Views | raywenderlich.com - It goes into more detail about how view builders work and how to leverage them yourself.

If that’s not at all what you’re asking, can you share an example of how you might think about the challenge in a way you’re more familiar with? That might help me give you a more helpful answer!

Hi Catie thanks for replying back
The solution for the challenge was solved by using multiple struct views I understand that struct view is base for swiftUI but my question
was can we have the same solved by using functions instead of views.Can we have one single view and move the reusable code to functions?
I want to understand what’s the criteria to decide to have structs and functions
Is it always preferable to write reusable functionality using views than functions?

It is possible in this case to use a computed property and a function instead of Views. The definitions would look like this, instead:

var currentConditions: some View {
func hourlyForecast(forecast: Weather.Forecast) -> some View {

This is slightly simpler code, so you may want to go this route instead. However…

  1. Xcode does not currently give the option to extract subviews into anything but views. It’s not hard to make a conversion, as I showed here, by deleting a couple of lines, but it is not a one-step process. And using extracted subviews instead of properties or functions has no performance impact.
  2. If you ever need to use Dynamic Properties, you’ll need to use Views. For example, there’s no way to utilize an @State variable in a function.

Thanks that’s informative

1 Like