[Swift] Type type-Class first part-

What is a class

A class is a type that has a structure similar to a struct.

There are two major differences from the structure. ** One is a reference type Two, inheritance is possible **

Definition method

Use the class keyword to define a class.


class class name{
Class definition
}

The methods, properties, and initializers that make up a type All are also available in classes and can be defined within {}.


class Sample {
    var value: Int
    var status: String
    
     init(value: Int, status: String) {
         self.value = value
         self.status = status
     }
    
    func printStatus() {
        print("value: \(value)\nstatus: \(status)")
    }
}


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

Execution result
value: 123
status: abc

Inheritance

Inheritance is when you define a new class ** A mechanism for reusing types such as methods, properties, and initializers of other classes. ** **

It ’s just inheritance, so It may be better to take over instead of reusing.

The inherited class does not need to define the same behavior as the inherited class, You only need to define the difference from the inheriting class.

The inheriting class is the ** superclass ** of the inheriting class. The inherited class is called a ** subclass ** of the inherited class.

Basically, the inherited class is the contents of the inherited class It will be defined in more detail.

** Note that Swift does not allow multiple inheritance from multiple classes. ** **

Definition method

If you want to define an inheritance relationship for a class Add : superclass after the class name.


class class name:Super class name{
Class definition
}

In the following sample code Set the class name of the inheriting class (super class) to Vehicle (vehicle) The class name of the inherited class (subclass) is Car.

** In the inherited Car class, defined in the inherited Vehicle class You can work with the name property and the printProfile () method. ** **

New in the Vehicle class You have defined the kind property and the newPrintProfile () method.

In the newPrintProfile () method, defined in the Vehicle class You are calling the printProfile () method.


class Vehicle {
    let name: String
    
    var message: String {
        return "Vehicle name:\(name)"
    }
    
    init(name: String) {
        self.name = name
    }
    
    func printProfile() {
        print(message)
    }
}

class Car: Vehicle {
    var kind: String
    
    init(name: String, kind: String) {
        self.kind = kind
        super.init(name: name)
    }
    
    func newPrintProfile() {
        printProfile()
        print("Vehicle type:\(kind)")
    }
}

let car = Car(name: "LEXUS LS", kind: "Automobile")
car.printProfile()
print("----")
car.newPrintProfile()

Execution result
Vehicle name: LEXUS LS
----
Vehicle name: LEXUS LS
Vehicle type: Car

In this way, you can eliminate duplicate descriptions by using inheritance. Therefore, when defining many similar classes, it is convenient to create a good inheritance relationship.

override

Overloads and overrides have similar names, but For overloading, prepare multiple methods with the same name that take arguments and return values ​​of different types. It is a method to switch the method to be executed according to the type passed to the argument and the type to which the return value is assigned.

** Overrides override elements such as properties and methods defined in the superclass A method of redefining in a subclass. ** **

Properties that can be overridden are Only ** instance properties ** and ** class properties ** described below.

That is, static properties cannot be overridden.

To do the override Use the override keyword to redefine the elements defined in the superclass.

Modify the previous sample code to some overrides.

PrintProfile () is described in the process in the newPrintProfile () method.

For processing the printProfile () method A new process print ("Vehicle type: \ (kind) ") has been added.

As much as defining a new newPrintProfile () method It's easier to overwrite (override) the printProfile () method. So I will override it.


class Vehicle {
    let name: String
    
    var message: String {
        return "Vehicle name:\(name)"
    }
    
    init(name: String) {
        self.name = name
    }
    
    func printProfile() {
        print(message)
    }
}

class Car: Vehicle {
    var kind: String
    
    init(name: String, kind: String) {
        self.kind = kind
        super.init(name: name)
    }
    
    //Override printProfile
    override func printProfile() {
        super.printProfile()
        print("Vehicle type:\(kind)")
    }
}

let car = Car(name: "LEXUS LS", kind: "Automobile")
car.printProfile()

Execution result
Vehicle name: LEXUS LS
Vehicle type: Car

In the code before overriding, The result of car.printProfile () was only the name of the vehicle.

But when I run car.printProfile () after overriding, In addition to the vehicle name, the vehicle type was output.

The printProfile () method says super.printProfile (). super refers to a superclass (inheritance source).

That is, you can read run the superclass (Vehicle) printProfile (). In addition to that, the overwritten print ("vehicle type: \ (kind) ") is also executed.

The processing contents in printProfile are as follows.


print(message)   // super.printProfile()Contents of
print("Vehicle type:\(kind)")

finel keyword

The final keyword can be written before the inheritable element. You can ** prevent that element from being overridden in subclasses **.

From the following sample code Methods without the finel keyword can be overwritten, You can see that the method with the final keyword cannot be overridden.


class SuperClass {
    func methodA() {}
    final func methodB() {}
}

class SubClass: SuperClass {
    override func methodA() {}
    override func methodB() {}   //Compile error
}

Error details: Instance method overrides a'final' instance method Instance method overrides "final" instance method

By adding the final keyword to the class itself It is prohibited to define a class that inherits that class.


class SuperClassA {}
final class SuperClassB {}

class SubClassA: SuperClassA {}
class SubClassB: SuperClassB {}   //Compile error

Error details: nheritance from a final class'SuperClassB' Japanese translation: Inheritance from the final class "super class"

If there are classes or methods that should not be inherited, Use the final keyword to prevent inheritance.

I wanted to write more, It seemed to be a considerable amount, so I would like to divide it into the first part and the second part.

Click here for the second part -> [Swift] Type Type ~ Class Part 2 ~

Thank you for watching until the end.

Recommended Posts

[Swift] Type type-Class first part-
[Swift] Type type-Class sequel-
[Swift] Type component ~ Property Part 2 ~
[Swift] Type type ~ Enumeration type ~
First Swift Lint
[Swift] First Firebase
[Swift] Type type ~ Structure ~
[Swift] Type components ~ Type nesting ~
[Swift] Type component ~ Subscript ~
[Swift] Type design guidelines
[Swift] Type component ~ Initializer ~
[Swift] Shared enumeration type
Swift Combine First step
[Swift] Type component ~ Method ~
[Swift] Summary about Bool type
Great Swift pointer type commentary
Introduction to swift practice output Type representing the Chapter 4 collection Part 1