Structs in Swift are value types that allow you to encapsulate related properties and behaviors into a single unit. They are similar to classes but have some key differences such as value semantics and lack of inheritance.
To declare a struct in Swift, you use the struct
keyword followed by the struct's name:
struct Person {
var name: String
var age: Int
}
You can create an instance of a struct by using the initializer syntax:
let person1 = Person(name: "Alice", age: 30)
let person2 = Person(name: "Bob", age: 25)}
You can access the properties of a struct using dot notation:
print(person1.name) // Output: Alice
print(person2.age) // Output: 25}
Unlike classes, which are reference types, structs are value types. This means that when you assign a struct instance to another variable or pass it as a function argument, a copy of the struct is created:
var person3 = person1
person3.name = "Eve"
print(person1.name) // Output: Alice
print(person3.name) // Output: Eve}
Structs can also have methods to perform operations on their properties:
struct Rectangle {
var width: Int
var height: Int
func area() -> Int {
return width * height
}
}
let rectangle = Rectangle(width: 10, height: 5)
print(rectangle.area()) // Output: 50}