Swift struct


Swift struct is a general and flexible construct for building code.

We can define properties (constants, variables) and add methods to the structure to extend the functionality of the structure.

The difference from C and Objective C is:

  • The structure does not need to contain implementation files and interfaces.

  • Structures allow us to create a single file, and the system will automatically generate external interfaces to other code.

The structure is always passed in the code by being copied, so its value cannot be modified.

Syntax

We define the structure through the keyword struct:

struct nameStruct { 
   Definition 1
   Definition 2
   ……
   Definition N
}

Example

We define a structure named MarkStruct, The attributes of the structure are the students' scores in three subjects, and the data type is Int:

struct MarkStruct{
   var mark1: Int
   var mark2: Int
   var mark3: Int
}

We can access the structure members through the structure name.

The structure is instantiated using the let keyword:

import Cocoa

struct studentMarks {
   var mark1 = 100
   var mark2 = 78
   var mark3 = 98
}
let marks = studentMarks()
print("Mark1 是 \(marks.mark1)")
print("Mark2 是 \(marks.mark2)")
print("Mark3 是 \(marks.mark3)")

The output result of the execution of the above program is:

Mark1 是 100
Mark2 是 78
Mark3 是 98

In the example, we pass the structure name 'studentMarks' accesses student marks. The structure members are initialized as mark1, mark2, mark3, and the data type is integer.

Then we instantiate the structure studentMarks() and pass it to marks by using the let keyword.

Finally, we access the value of the structure members through the . number.

The following instantiation passes a value when instantiating a structure and clones a structure:

import Cocoa

struct MarksStruct {
   var mark: Int

   init(mark: Int) {
      self.mark = mark
   }
}
var aStruct = MarksStruct(mark: 98)
var bStruct = aStruct // aStruct 和 bStruct 是使用相同值的结构体!
bStruct.mark = 97
print(aStruct.mark) // 98
print(bStruct.mark) // 97

The output result of the execution of the above program is:

98
97

Structure application

In your code, you can use structures to define your custom data types.

Structure instances are always passed by value to define your custom data type.

As a general guideline, please consider building a structure when one or more of the following conditions are met:

  • The main purpose of a structure is to encapsulate a small number of related Simple data value.

  • There is reason to expect that when a structure instance is assigned or passed, the encapsulated data will be copied rather than referenced.

  • Any value type attributes stored in the structure will also be copied instead of referenced.

  • A structure does not need to inherit the properties or behavior of another existing type.

For example, the structure is suitable for use in the following situations:

  • The size of the geometric shape, encapsulating a width Property and height property, both of which are of type Double.

  • A path within a certain range, encapsulating a start attribute and a length attribute, both of which are of type Int .

  • A point in the three-dimensional coordinate system encapsulates the x, y and z attributes, all three are Double type.

Structure instances are passed by value rather than by reference.

import Cocoa

struct markStruct{
    var mark1: Int
    var mark2: Int
    var mark3: Int
    
    init(mark1: Int, mark2: Int, mark3: Int){
        self.mark1 = mark1
        self.mark2 = mark2
        self.mark3 = mark3
    }
}

print("优异成绩:")
var marks = markStruct(mark1: 98, mark2: 96, mark3:100)
print(marks.mark1)
print(marks.mark2)
print(marks.mark3)

print("糟糕成绩:")
var fail = markStruct(mark1: 34, mark2: 42, mark3: 13)
print(fail.mark1)
print(fail.mark2)
print(fail.mark3)

The execution output of the above program is:

优异成绩:
98
96
100
糟糕成绩:
34
42
13

In the above example, we defined the structure markStruct, with three member attributes: mark1, mark2 and mark3. When using member properties within a structure, use the self keyword.

From the example, we can well understand that the structure instance is passed by value.