In Swift, a structure is a user-defined data type that allows us to encapsulate related properties and behaviors together. Structures provide a way to create reusable pieces of code and can be used to represent real-world objects or concepts.
To define a structure in Swift, we use the struct
keyword followed by the structure's name. Let's create a simple example of a Person
structure:
struct Person { var name: String var age: Int var height: Double }
In the above code snippet, we have defined a
Person
structure with three properties:name
,age
, andheight
. The properties represent the name, age, and height of a person.We can create instances of the
Person
structure by using the initializer provided by Swift:let john = Person(name: "John Doe", age: 30, height: 175.5) let jane = Person(name: "Jane Smith", age: 25, height: 163.2)
Once we have created an instance of a structure, we can access its properties using dot notation:
print(john.name) // Output: "John Doe" print(jane.age) // Output: 25
Structures can also have methods associated with them. These methods can be used to perform actions or calculations using the structure's properties. Let's add a method to our
Person
structure:struct Person { var name: String var age: Int var height: Double func greet() { print("Hello, my name is \(name)!") } }
Now, we can call the
greet
method on an instance of thePerson
structure:john.greet() // Output: "Hello, my name is John Doe!" jane.greet() // Output: "Hello, my name is Jane Smith!"
Structures in Swift are value types, which means they are copied when assigned to a new constant or variable, or when they are passed as a parameter to a function. This behavior is different from reference types, such as classes, which are passed by reference.
Summary: Structures in Swift allow us to define custom data types that encapsulate related properties and behaviors. They provide a way to create reusable code and represent real-world objects or concepts.