[Swift] Type type ~ Structure ~

What is a structure?

Structures are a type of value, One value is represented by a combination of stored properties.

There are many examples of using structures. For example, many types provided in the standard library are structures.

Bool type, numeric type, String type, Array \ type are all structures.

Types that are not structs Optional \ type, tuple type, Any type, etc.

Definition method

Use the struct keyword to define the structure.


struct structure name{
Structure definition
}

Properties, methods, initializers, etc. All of the elements that make up the type are available and are defined in {}.


struct Sample {
    let number: Int
    let name: String
    
    init(number: Int, name: String) {
        self.number = number
        self.name = name
    }
    
    func printStatus() {
        print("name:\(name)\n number:\(number)Turn")
    }
}

let a = Sample(number: 1, name: "Aihara")
a.printStatus()

Execution result
Name: Aihara
Number: No. 1

Change of value by changing stored property

As mentioned earlier, a struct is a combination of stored properties. Changing a struct's stored properties is equivalent to changing the struct to another value, It requires reassignment of constants and variables that contain structures.

Therefore, the specification for changing the value of ** value type is It also applies to changing stored properties of structures. ** **

Constant stored properties cannot be changed

Since changing the stored properties of the structure requires reassignment, The stored property of the structure assigned to the constant cannot be changed.

It is as shown in the sample code below.


struct Sample {
    var value: Int
    
    init(value: Int) {
        self.value = value
    }
}

var a = Sample(value: 1)
a.value = 2   // OK

let b = Sample(value: 1)
b.value = 3   //Compile error

Error details: Cannot assign to property:'b' is a'let' constant Japanese translation: Cannot be assigned to a property: "b" is a "let" constant

Modify stored properties in a method

To change a stored property with a method defined in a structure You need to add the muting keyword to the beginning of the method.


struct Sample {
    var value: Int
    
    init(value: Int) {
        self.value = value
    }
    
    mutating func increment() {
        value += 1
    }
}

var a = Sample(value: 1)
a.increment()
a.value   // 2

Changes to stored properties within the method are checked by the compiler.

So for methods that involve changing stored properties If the mutating keyword is not added, a compile error will occur.

Below is the pattern without the mating keyword added.


struct Sample {
    var value: Int
    
    init(value: Int) {
        self.value = value
    }
    
    func increment() {
        value += 1   //Compile error
    }
}

var a = Sample(value: 1)
a.increment()

Error details: Left side of mutating operator isn't mutable:'self' is immutable Japanese translation: The left side of the change operator cannot be changed: "self" cannot be changed

Member Wise Initializer

An instance of a type must have all its properties initialized after it is initialized.

Therefore, it may be initialized when the property is defined. I had defined and initialized my own initializer.

But ** structs are automatically defined You can use the member-wise initializer. ** **

What is a member-wise initializer? An initializer that takes an argument with the same name as each stored property that the type has.

In the case of the sample code below Because there are two stored properties, value and status The memberwise initializer will be init (value: Int, status: String).

Also, the member wise initializer It can be used in the same way as a normal initializer.


struct Sample {
    var value: Int
    var status: String
    
    //Automatically generated
    // init(value: Int, status: String) {
    //     self.value = value
    //     self.status = status
    // }

}

let a = Sample(value: 123, status: "abc")
a.value   // 123
a.status   // abc

Default argument for member-wise initializer

If the stored property was initialized at definition time The memberwise initializer argument that corresponds to that property is ** It has a default argument and you can omit the specification of the argument at the time of calling. ** **

Of course it only has default arguments, so You can also specify the arguments as usual.

In the following sample code Defines a structure that has the stored properties value and status.

value is initialized and 10 is assigned.

In this case, the argument value of the memberwise initializer is The default argument 10 is defined.


struct Sample {
    var value: Int = 10
    var status: String
    
    //Automatically generated
    // init(value: Int = 10, status: String) {
    //     self.value = value
    //     self.status = status
    // }
}

let a = Sample(status: "abc")
a.value   // 10
a.status   // abc

let b = Sample(value: 123, status: "def")
b.value   // 123
b.status   // def

The above is the explanation of the structure.

I want to be able to make good use of mold components to create highly convenient structures.

I think that there is no choice but to use the structure more and more for that, so I want to output more and more!

I also have articles about classes, enums, and basic knowledge of types. Please take a look when you have time!

[Swift] Type type ~ Basic knowledge ~[Swift] Type Type-Class Part 1-[Swift] Type type ~ Enumeration ~

Thank you for watching until the end.

Recommended Posts

[Swift] Type type ~ Structure ~
[Swift] Type type ~ Enumeration type ~
[Swift] Type components ~ Type nesting ~
[Swift] Type component ~ Subscript ~
[Swift] Type design guidelines
[Swift] Type component ~ Initializer ~
[Swift] Shared enumeration type
[Swift] Type type-Class sequel-
[Swift] Type component ~ Method ~
[Swift] Summary about Bool type
[Swift] Type component ~ Property Part 2 ~
Great Swift pointer type commentary
[Swift] Converts a UInt64 type integer to [UInt8]
Pass type
[Swift] Closure
data structure
Directory type
Human type
[Swift / For beginners] Write smartly with type inference
[Swift] Perform error handling with Optional <Wrapped> type
Convert from C String pointer to Swift String type