The “struct”

When you create a new SwiftUI View file, you will be presented with the default code to get you started—and to stop Xcode from showing an error. Simply put, there needs to be something between the the curly braces {} when you declare body. In this case, the body at least contains a Text() view discussed previously.

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")

Starting at the top, first you import the SwiftUI library. You won’t need to change this or worry about adding a new library for now. This is followed by the meat of the file, the struct.

The struct is the building block of your code. When you start, the first two structs created in the Swift file are both named after your filename. The second struct with the _Previews: PreviewProvider suffix is the bit of code that creates the preview of your design. The single view inside this struct calls the first struct. In other words, this tells the Preview window to display a preview of the main struct where the real layout will be. When your app is built, this will be ignored.

The first struct will contain all the SwiftUI to show your layout. For now we’ll focus on the one variable (var) called body which is some View. This defines a variable that will contain a View inside the braces. And in this case all it contains is Text("Hello, World!"). You can actually only return one view inside View, but the trick is to make that view a wrapper for all your own SwiftUI elements.

A SwfitUI View file can contain numerous separate structs to build your layout. Again this file is like your Figma artboard—it’s the frame that all your elements will be grouped inside. Each struct is its own group or component. And you can break down your design into reusable components by moving repeated elements into their own struct

© 2024 SwitftUI Prototyping