/

SwiftUI: Properties

SwiftUI: Properties

In SwiftUI, you have the flexibility to add properties to any view to enhance its functionality. Let’s explore how properties can be used in SwiftUI views.

1
2
3
4
5
6
7
8
9
10
import SwiftUI

struct ContentView: View {
let name = "Flavio"

var body: some View {
Text("Hello, \(name)!")
.font(.largeTitle)
}
}

Image: Screen_Shot_2021-09-13_at_14.55.12.png

In the above code snippet, we declare a constant property name of type String and assign it the value “Flavio”. This property is then used within the Text view to display a personalized greeting.

It’s important to note the use of the let keyword for the property since it is a constant value.

Let’s explore another example with an integer variable:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import SwiftUI

struct ContentView: View {
let name = "Flavio"
let age = 38

var body: some View {
VStack {
Text("Hello, \(name)!")
.font(.largeTitle)
Text("You are \(age) years old")
}
}
}

Image: Screen_Shot_2021-09-13_at_15.11.39.png

In this example, we introduce a new property age of type Int, which stores the value 38. The VStack view is used to stack multiple views vertically, containing the personalized greeting and the display of the age.

By leveraging properties, you can easily customize your SwiftUI views and dynamically update their content based on your needs. In the next section, we’ll explore how to update property values by implementing user interactions.

tags: [“SwiftUI”, “properties”, “view properties”, “constant properties”, “variable properties”]