Javatpoint Logo
Javatpoint Logo

Swift Structures

Swift structures are the flexible basic building blocks of the programs. The "struct" keyword is used to define structures. By using structures, you can define constructs methods and properties.

Syntax:

You need to make instances of that structure to make use of structure properties. Dot operator is used to access properties of structures.

Swift Structures vs C Structure/ Objective-C Structure

Unlike the C structures and Object-C structures, the Swift structures don't require implementation files and interface. Also, Swift structures allow us to create a single file and to extend its interface automatically to other blocks.

Note: In Structure, the variable values are copied and passed in subsequent codes by returning a copy of the old values so we cannot alter the values.

Definition of a structure

Suppose, you have to access your bank account having some amount in rupees and paisa here, Here Amount is structure's name which is used to initialize a structure with rupees and paisa as datatype 'Int'

Access the structure and its properties

Let's see the implementation of the structures in Swift. Here, we shall assign some values in structure and then access them.

Example:

Output:

Amount(rupees: 10000, paisa: 50)
Amount in rupees is 10000
Amount in paisa is 50 

Here, structure's name is "Amount" and there are two variables used "rupees" and "paisa" which are later accessed by using print statement and dot operator.

Swift Structure Usage

Swift4 language facilitates you to define structures as custom data types for building the function blocks. The instances of structure are passed by its value to the defined blocks for further changes.

  • Structures are used to encapsulate simple data values.
  • Structures are used to copy the encapsulated data and its associated properties by 'values' rather than by 'references'.

Next TopicSwift Classes




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA