Group Group Group Group Group Group Group Group Group

Not fully understanding structs, code, and constructors in views

Let me give an example …

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(taskStore: TaskStore() )

Here we have a structure of type PreviewProvider. It has a variable called previews. I’m not sure what “some View” means, but it appears to be the type. Inside the variable is what appears to be a function call. (However, that function call is not made inside a code block. There is no function declared within the structure to be making function calls.) However, that function call is to a data type “ContentView”. Am I correct in assuming that it is calling the constructor for that data type? (Shouldn’t the result of the constructor call be assigned to a variable?) Likewise, it is passing a variable called taskStore, which appears to be created by calling another constructor. However, I don’t see constructors defined for either one of these things. It is just like making the fucnction calls creates the objects?

Best wishes,

John Coffey

Hi @john2001plus,
There is a lot of internal wiring that happens with SwiftUI.

A View is a generic term for things like Text, Button, etc. So instead of specifically returning a type of view, Swift offers a way of returning any type of View.

When we create a structure of type PreviewProvided, it has a static variable called previews, this needs to return a type of view as explained above.

In the preview the function ContentView would return the view and it takes a parameter which is returned from initialization of TaskStore. Look at the declaration of the ContentView.

You might want to read a bit more on ‘some’.