Using a struct in Swift is straightforward and very common for modeling data. Structs in Swift are value types, meaning they are copied when passed around in your code, as opposed to classes which are reference types.
Here's a breakdown of the correct and idiomatic way to use a struct in Swift:
✅ Defining a Struct
swift
struct User {
var name: String
var age: Int
func greet() {
print("Hello, my name is \(name) and I am \(age) years old.")
}
}
✅ Creating an Instance
swift
var user = User(name: "Alice", age: 30)
Swift automatically provides a memberwise initializer for structs (unless you provide your own).
✅ Accessing and Modifying Variables
swift
print(user.name) // Alice
user.age = 31
print(user.age) // 31
Note: You must declare the instance as var to modify its properties because it's a value type.
✅ Using Methods
swift
user.greet()
// Output: Hello, my name is Alice and I am 31 years old.
✅ Mutating Methods
If a method needs to modify self or any of its properties, you must use the mutating keyword: