In Swift, struct
is a value type that allows you to define your own data structure. It is similar to a class, but with some important differences.
To define a struct in Swift, you can use the struct
keyword followed by the name of the struct. Inside the struct, you can define properties and methods.
Here's an example of how to define a struct in Swift:
main.swift158 chars9 lines
In the example above, we defined a struct called Person
with two properties: name
and age
. We also defined a method called sayHello()
that prints a greeting message with the person's name and age.
To create an instance of a struct, you can simply use the name of the struct followed by parentheses and provide values for the properties:
main.swift41 chars2 lines
You can access the properties and call the methods of a struct instance using dot notation:
main.swift110 chars3 lines
One important thing to note about structs is that they are value types. This means that when you assign a struct instance to a new variable or pass it as a parameter to a function, a copy of the struct is created.
main.swift106 chars6 lines
In the example above, changing the name
property of jane
does not affect the name
property of john
, because they are separate instances of the Person
struct.
Structs are commonly used in Swift to represent simple data models, such as coordinates, sizes, or person information. They can also be used to encapsulate related data and behavior into a single unit.
gistlibby LogSnag