Date: 21/06/2025
Author: Bruno
Here we going to cover several key Swift and SwiftUI concepts, including button views, variables differences between var
& let
, stored properties, the @State
property wrapper, and debugging with print()
. Below is a detailed breakdown of these topics.
var
vs. let
In Swift, variables can be declared in two ways:
var
– Mutable (can be changed after declaration).let
– Immutable (cannot be changed after declaration).In Swift, struct
(value types) properties are immutable by default. This means you cannot modify a struct’s property unless:
var
.@State
.without @State
struct MyView: View {
var title: String = "Hello" // Immutable (cannot modify inside the view)
}
with @State
struct MyView: View {
@State var title: String = "Hello" // Mutable due to @State
}
The .toggle()
method inverts a boolean value:
@State var showExchangeInfo = false
Button("Toggle") {
showExchangeInfo.toggle() // Changes false → true or true → false
print("Current state: \(showExchangeInfo)")}
SwiftUI makes UI building declarative, which means you define what the interface should look like and how it should react to state changes. Adding and modifying button views is simple:
Button("Tap Me") {
print("Button tapped")}
You can customize these views further using modifiers like .padding(), .background(), .foregroundColor()
, and others.
Using print()
Helps debug by logging values to the console:
print("Show Exchange Info: \(showExchangeInfo)")
String Interpolation
The values inside the parentheses “\()”
are evaluated and converted into their string representation before being inserted into the string. This is incredibly useful for testing, as you can see the exact values of your properties at different points in your code.
let name = "Bruno"
print("Hello, \(name)!") // Output: "Hello, Bruno!"
SwiftUI provides view modifiers to adjust layout, such as:
.padding()
– Adds equal padding on all sides..padding(.trailing)
– Adds padding only on the right..leading
, .top
, .bottom
, .horizontal
, .vertical
.