Swift - Get to know Structures


A structure is a data type that groups a list of variables and places them under a unified name.

The group of variables contained within a structure may have different data types.

For example, to represent a pawn on the check board, use a structure containing two variables: row and column.

The following code defines the structure named Chess:

struct Chess {
    var row = 0      //0...7 
    var column = 0   //0...7

For structure names, the recommendation is to use UpperCamelCase.

The Chess structure has two properties called row and column , which are both initialized to 0 (their default values).

To create an instance of the Chess structure, use the structure's default initializer syntax:

var c = Chess ()

The preceding creates an instance of the Chess structure, and the instance name is c.

The property row and column are both initialized to 0 by default:

var c = Chess ()
print(c.row)      //0
print(c.column)   //0

You access the properties using the dot . syntax.

Just as you can access the value of the property, you can also change its value:

c.row = 2        //change the row to 2
c.column = 6     //change the column to 6

Related Topic