A struct in Swift is a data structure that can hold variables of different data types. It can also have functions defined in it.
struct structName{
// variables
// functions
}
struct Student {var name = ""var age = 0}print(Student())
A structure called Student
that consists of name
and age
as variables is created.
Structures are just a blueprint. To use any structure as such, we need to create an instance/object of the structure.
We can access the individual variables of a structure using the dot .
notation. The variables can be accessed using the objects/instances created from the structure.
struct Student {var name = ""var age = 0}var student = Student()student.name = "john"student.age = 23print(Student())print(student.name)print(student.age)
Student
struct.name
and age
variables of the structure using the .
notation.A structure can also have functions defined in them. To invoke those functions, we use the .
notation.
struct Student {var name = ""var age = 0func display(){print("Student[name=\(name),age=\(age)]")}}var student = Student()student.name = "john"student.age = 23student.display()
display()
function using the .
notation.