継承
日本語を消す 英語を消す下記URLから引用し、日本語訳をつけてみました。
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/inheritance
Subclass to add or override functionality.
機能を追加またはオーバーライドするサブクラス。
A class can inherit methods, properties, and other characteristics from another class. When one class inherits from another, the inheriting class is known as a subclass, and the class it inherits from is known as its superclass. Inheritance is a fundamental behavior that differentiates classes from other types in Swift.
クラスは、メソッド、プロパティ、その他の特性を別のクラスから継承できます。 あるクラスが別のクラスを継承する場合、継承するクラスはサブクラスと呼ばれ、継承元のクラスはスーパークラスと呼ばれます。 継承は、Swift のクラスを他の型から区別する基本的な動作です。
Classes in Swift can call and access methods, properties, and subscripts belonging to their superclass and can provide their own overriding versions of those methods, properties, and subscripts to refine or modify their behavior. Swift helps to ensure your overrides are correct by checking that the override definition has a matching superclass definition.
Swift のクラスは、スーパークラスに属するメソッド、プロパティ、および添字を呼び出してアクセスでき、それらのメソッド、プロパティ、および添字の独自のオーバーライド バージョンを提供して、動作を調整または変更できます。 Swift は、オーバーライド定義に一致するスーパークラス定義があるかどうかをチェックすることで、オーバーライドが正しいことを確認するのに役立ちます。
Classes can also add property observers to inherited properties in order to be notified when the value of a property changes. Property observers can be added to any property, regardless of whether it was originally defined as a stored or computed property.
クラスは、プロパティの値が変更されたときに通知を受けるために、継承されたプロパティにプロパティ オブザーバーを追加することもできます。 プロパティ オブザーバーは、最初に保存プロパティとして定義されたか、計算プロパティとして定義されたかに関係なく、任意のプロパティに追加できます。
Defining a Base Class
基本クラスの定義
Any class that doesn’t inherit from another class is known as a base class.
別のクラスを継承しないクラスは、基本クラスと呼ばれます。
Note
注釈
Swift classes don’t inherit from a universal base class. Classes you define without specifying a superclass automatically become base classes for you to build upon.
Swift クラスはユニバーサル基本クラスを継承しません。 スーパークラスを指定せずに定義したクラスは、自動的に基本クラスになり、その上に構築されます。
The example below defines a base class called Vehicle. This base class defines a stored property called currentSpeed, with a default value of 0.0 (inferring a property type of Double). The currentSpeed property’s value is used by a read-only computed String property called description to create a description of the vehicle.
以下の例では、Vehicle という基本クラスを定義しています。 この基本クラスは、currentSpeed という保存されたプロパティを定義し、デフォルト値は 0.0 です(Double のプロパティ タイプを推測)。 currentSpeed プロパティの値は、車両の説明を作成するために、description と呼ばれる読み取り専用の計算String プロパティによって使用されます。
The Vehicle base class also defines a method called makeNoise. This method doesn’t actually do anything for a base Vehicle instance, but will be customized by subclasses of Vehicle later on:
Vehicle 基本クラスは、makeNoise と呼ばれるメソッドも定義します。 このメソッドは実際には基本の Vehicle インスタンスに対して何も行いませんが、後で Vehicle のサブクラスによってカスタマイズされます。
class Vehicle {
var currentSpeed = 0.0
var description: String {
return "traveling at \(currentSpeed) miles per hour"
}
func makeNoise() {
// do nothing - an arbitrary vehicle doesn't necessarily make a noise
}
}
You create a new instance of Vehicle with initializer syntax, which is written as a type name followed by empty parentheses:
イニシャライザ構文を使用して、Vehicle の新しいインスタンスを作成します。イニシャライザ構文は、型名の後に空の括弧を続けて記述します。
let someVehicle = Vehicle()
Having created a new Vehicle instance, you can access its description property to print a human-readable description of the vehicle’s current speed:
新しい Vehicle インスタンスを作成したら、その description プロパティにアクセスして、人間が判読できる車両の現在の速度の説明を出力できます。
print("Vehicle: \(someVehicle.description)")
// Vehicle: traveling at 0.0 miles per hour
The Vehicle class defines common characteristics for an arbitrary vehicle, but isn’t much use in itself. To make it more useful, you need to refine it to describe more specific kinds of vehicles.
Vehicle クラスは、任意の車両に共通の特性を定義しますが、それ自体ではあまり役に立ちません。 これをより便利にするには、より具体的な種類の車両を記述できるように改良する必要があります。
Subclassing
サブクラス化
Subclassing is the act of basing a new class on an existing class. The subclass inherits characteristics from the existing class, which you can then refine. You can also add new characteristics to the subclass.
サブクラス化とは、既存のクラスに基づいて新しいクラスを作成する行為です。 サブクラスは既存のクラスから特性を継承し、その後、その特性を調整できます。 サブクラスに新しい特性を追加することもできます。
To indicate that a subclass has a superclass, write the subclass name before the superclass name, separated by a colon:
サブクラスにスーパークラスがあることを示すには、スーパークラス名の前にサブクラス名をコロンで区切って記述します。
class SomeSubclass: SomeSuperclass {
// subclass definition goes here
}
The following example defines a subclass called Bicycle, with a superclass of Vehicle:
次の例では、Vehicle のスーパークラスを使用して、Bicycle というサブクラスを定義しています。
class Bicycle: Vehicle {
var hasBasket = false
}
The new Bicycle class automatically gains all of the characteristics of Vehicle, such as its currentSpeed and description properties and its makeNoise() method.
新しい Bicycle クラスは、currentSpeed プロパティと description プロパティ、makeNoise() メソッドなど、Vehicle のすべての特性を自動的に取得します。
In addition to the characteristics it inherits, the Bicycle class defines a new stored property, hasBasket, with a default value of false (inferring a type of Bool for the property).
継承する特性に加えて、Bicycle クラスは新しい格納プロパティ hasBasket を定義し、デフォルト値は false です(プロパティの Bool 型を推測します)。
By default, any new Bicycle instance you create will not have a basket. You can set the hasBasket property to true for a particular Bicycle instance after that instance is created:
デフォルトでは、作成する新しい自転車インスタンスにはバスケットがありません。 特定の Bicycle インスタンスの作成後に、そのインスタンスの hasBasket プロパティを true に設定できます。
let bicycle = Bicycle()
bicycle.hasBasket = true
You can also modify the inherited currentSpeed property of a Bicycle instance, and query the instance’s inherited description property:
また、Bicycle インスタンスの継承された currentSpeed プロパティを変更し、インスタンスの継承された description プロパティをクエリすることもできます。
bicycle.currentSpeed = 15.0
print("Bicycle: \(bicycle.description)")
// Bicycle: traveling at 15.0 miles per hour
Subclasses can themselves be subclassed. The next example creates a subclass of Bicycle for a two-seater bicycle known as a “tandem”:
サブクラス自体をサブクラス化できます。 次の例では、「タンデム」と呼ばれる 2 人乗り自転車用の Bicycle のサブクラスを作成します。
class Tandem: Bicycle {
var currentNumberOfPassengers = 0
}
Tandem inherits all of the properties and methods from Bicycle, which in turn inherits all of the properties and methods from Vehicle. The Tandem subclass also adds a new stored property called currentNumberOfPassengers, with a default value of 0.
Tandem は、Bicycle からすべてのプロパティとメソッドを継承し、Bicycle はすべてのプロパティとメソッドを Vehicle から継承します。 Tandem サブクラスは、currentNumberOfPassengers という新しい保存プロパティも追加します。デフォルト値は 0 です。
If you create an instance of Tandem, you can work with any of its new and inherited properties, and query the read-only description property it inherits from Vehicle:
Tandem のインスタンスを作成すると、その新しい継承されたプロパティのいずれかを操作し、Vehicle から継承した読み取り専用の記述プロパティをクエリできます。
let tandem = Tandem()
tandem.hasBasket = true
tandem.currentNumberOfPassengers = 2
tandem.currentSpeed = 22.0
print("Tandem: \(tandem.description)")
// Tandem: traveling at 22.0 miles per hour
Overriding
オーバーライド
A subclass can provide its own custom implementation of an instance method, type method, instance property, type property, or subscript that it would otherwise inherit from a superclass. This is known as overriding.
サブクラスは、スーパークラスから継承するインスタンス メソッド、型メソッド、インスタンス プロパティ、型プロパティ、またはサブスクリプトの独自のカスタム実装を提供できます。 これはオーバーライドと呼ばれます。
To override a characteristic that would otherwise be inherited, you prefix your overriding definition with the override keyword. Doing so clarifies that you intend to provide an override and haven’t provided a matching definition by mistake. Overriding by accident can cause unexpected behavior, and any overrides without the override keyword are diagnosed as an error when your code is compiled.
継承される特性をオーバーライドするには、オーバーライド定義の前に override キーワードを付けます。 そうすることで、オーバーライドを提供するつもりであり、一致する定義を誤って提供していないことが明確になります。 誤ってオーバーライドすると予期しない動作が発生する可能性があり、override キーワードを指定しないオーバーライドはコードのコンパイル時にエラーとして診断されます。
The override keyword also prompts the Swift compiler to check that your overriding class’s superclass (or one of its parents) has a declaration that matches the one you provided for the override. This check ensures that your overriding definition is correct.
また、override キーワードは、オーバーライドするクラスのスーパークラス (またはその親の 1 つ) に、オーバーライドに指定した宣言と一致する宣言があるかどうかを Swift コンパイラーに確認するように促します。 このチェックにより、オーバーライド定義が正しいことが確認されます。
Accessing Superclass Methods, Properties, and Subscripts
スーパークラスのメソッド、プロパティ、サブスクリプトへのアクセス
When you provide a method, property, or subscript override for a subclass, it’s sometimes useful to use the existing superclass implementation as part of your override. For example, you can refine the behavior of that existing implementation, or store a modified value in an existing inherited variable.
サブクラスのメソッド、プロパティ、または添字オーバーライドを提供する場合、オーバーライドの一部として既存のスーパークラス実装を使用すると便利な場合があります。 たとえば、既存の実装の動作を調整したり、変更した値を既存の継承変数に保存したりできます。
Where this is appropriate, you access the superclass version of a method, property, or subscript by using the super prefix:
これが適切な場合は、super 接頭辞を使用して、メソッド、プロパティ、またはサブスクリプトのスーパークラス バージョンにアクセスします。
- An overridden method named
someMethod()can call the superclass version ofsomeMethod()by callingsuper.someMethod()within the overriding method implementation. someMethod()という名前のオーバーライドされたメソッドは、オーバーライドするメソッド実装内でsuper.someMethod()を呼び出すことで、someMethod()のスーパークラス バージョンを呼び出すことができます。- An overridden property called
somePropertycan access the superclass version ofsomePropertyassuper.somePropertywithin the overriding getter or setter implementation. somePropertyと呼ばれるオーバーライドされたプロパティは、オーバーライドするgetterまたはsetter実装内でsuper.somePropertyとしてsomePropertyのスーパークラス バージョンにアクセスできます。- An overridden subscript for
someIndexcan access the superclass version of the same subscript assuper[someIndex]from within the overriding subscript implementation. someIndexのオーバーライドされたサブスクリプトは、オーバーライドするサブスクリプト実装内からsuper[someIndex]として同じサブスクリプトのスーパークラス バージョンにアクセスできます。
Overriding Methods
メソッドのオーバーライド
You can override an inherited instance or type method to provide a tailored or alternative implementation of the method within your subclass.
継承されたインスタンスまたは型メソッドをオーバーライドして、サブクラス内でメソッドの調整された実装または代替実装を提供することができます。
The following example defines a new subclass of Vehicle called Train, which overrides the makeNoise() method that Train inherits from Vehicle:
次の例では、Train という Vehicle の新しいサブクラスを定義します。これは、Train が Vehicle から継承する makeNoise() メソッドをオーバーライドします。
class Train: Vehicle {
override func makeNoise() {
print("Choo Choo")
}
}
If you create a new instance of Train and call its makeNoise() method, you can see that the Train subclass version of the method is called:
Train の新しいインスタンスを作成し、その makeNoise() メソッドを呼び出すと、メソッドの Train サブクラス バージョンが呼び出されることがわかります。
let train = Train()
train.makeNoise()
// Prints "Choo Choo"
Overriding Properties
プロパティの上書き
You can override an inherited instance or type property to provide your own custom getter and setter for that property, or to add property observers to enable the overriding property to observe when the underlying property value changes.
継承されたインスタンスまたは型プロパティをオーバーライドして、そのプロパティに独自のカスタム ゲッターおよびセッターを提供したり、プロパティ オブザーバーを追加して、基になるプロパティ値が変更されたときにオーバーライドするプロパティが監視できるようにしたりできます。
Overriding Property Getters and Setters
プロパティのゲッターとセッターをオーバーライドする
You can provide a custom getter (and setter, if appropriate) to override any inherited property, regardless of whether the inherited property is implemented as a stored or computed property at source. The stored or computed nature of an inherited property isn’t known by a subclass — it only knows that the inherited property has a certain name and type. You must always state both the name and the type of the property you are overriding, to enable the compiler to check that your override matches a superclass property with the same name and type.
カスタムのゲッター(および必要に応じてセッター)を提供して、継承されたプロパティがソースで保存プロパティとして実装されているか計算プロパティとして実装されているかに関係なく、継承されたプロパティをオーバーライドできます。 継承されたプロパティの保存された性質または計算された性質は、サブクラスには認識されません。サブクラスは、継承されたプロパティが特定の名前と型を持つことのみを知っています。 オーバーライドが同じ名前と型のスーパークラス プロパティと一致するかどうかをコンパイラがチェックできるように、オーバーライドするプロパティの名前と型の両方を常に指定する必要があります。
You can present an inherited read-only property as a read-write property by providing both a getter and a setter in your subclass property override. You can’t, however, present an inherited read-write property as a read-only property.
サブクラスのプロパティ オーバーライドでゲッターとセッターの両方を指定することにより、継承された読み取り専用プロパティを読み取り/書き込みプロパティとして提示できます。 ただし、継承された読み取り/書き込みプロパティを読み取り専用プロパティとして提示することはできません。
Note
注釈
If you provide a setter as part of a property override, you must also provide a getter for that override. If you don’t want to modify the inherited property’s value within the overriding getter, you can simply pass through the inherited value by returning super.someProperty from the getter, where someProperty is the name of the property you are overriding.
プロパティ オーバーライドの一部としてセッターを提供する場合は、そのオーバーライドのゲッターも提供する必要があります。 オーバーライドするゲッター内で継承されたプロパティの値を変更したくない場合は、ゲッターから super.someProperty を返すことで単純に継承された値を渡すことができます。ここで、someProperty はオーバーライドするプロパティの名前です。
The following example defines a new class called Car, which is a subclass of Vehicle. The Car class introduces a new stored property called gear, with a default integer value of 1. The Car class also overrides the description property it inherits from Vehicle, to provide a custom description that includes the current gear:
次の例では、Vehicle のサブクラスである Car という新しいクラスを定義します。 Car クラスには、デフォルトの整数値 1 を持つ、gear という新しい保存プロパティが導入されています。また、Car クラスは、Vehicle から継承する description プロパティをオーバーライドして、現在のギアを含むカスタムの説明を提供します。
class Car: Vehicle {
var gear = 1
override var description: String {
return super.description + " in gear \(gear)"
}
}
The override of the description property starts by calling super.description, which returns the Vehicle class’s description property. The Car class’s version of description then adds some extra text onto the end of this description to provide information about the current gear.
description プロパティのオーバーライドは、super.description を呼び出すことで開始され、Vehicle クラスの description プロパティが返されます。 次に、Car クラスの説明のバージョンは、この説明の最後に追加のテキストを追加して、現在のギアに関する情報を提供します。
If you create an instance of the Car class and set its gear and currentSpeed properties, you can see that its description property returns the tailored description defined within the Car class:
Car クラスのインスタンスを作成し、その gear プロパティと currentSpeed プロパティを設定すると、その description プロパティが Car クラス内で定義された調整された説明を返すことがわかります。
let car = Car()
car.currentSpeed = 25.0
car.gear = 3
print("Car: \(car.description)")
// Car: traveling at 25.0 miles per hour in gear 3
Overriding Property Observers
プロパティオブザーバーのオーバーライド
You can use property overriding to add property observers to an inherited property. This enables you to be notified when the value of an inherited property changes, regardless of how that property was originally implemented. For more information on property observers, see Property Observers.
プロパティのオーバーライドを使用して、継承されたプロパティにプロパティ オブザーバーを追加できます。 これにより、プロパティが最初にどのように実装されたかに関係なく、継承されたプロパティの値が変更されたときに通知を受け取ることができます。 プロパティ オブザーバーの詳細については、「プロパティ オブザーバー」を参照してください。
Note
注釈
You can’t add property observers to inherited constant stored properties or inherited read-only computed properties. The value of these properties can’t be set, and so it isn’t appropriate to provide a willSet or didSet implementation as part of an override.
継承された定数格納プロパティまたは継承された読み取り専用の計算プロパティにプロパティ オブザーバーを追加することはできません。 これらのプロパティの値は設定できないため、オーバーライドの一部として willSet または didSet の実装を提供することは適切ではありません。
Note also that you can’t provide both an overriding setter and an overriding property observer for the same property. If you want to observe changes to a property’s value, and you are already providing a custom setter for that property, you can simply observe any value changes from within the custom setter.
また、同じプロパティに対してオーバーライド セッターとオーバーライド プロパティ オブザーバーの両方を指定することはできないことにも注意してください。 プロパティの値の変更を監視する必要があり、そのプロパティにカスタム セッターをすでに提供している場合は、カスタム セッター内から値の変更を簡単に監視できます。
The following example defines a new class called AutomaticCar, which is a subclass of Car. The AutomaticCar class represents a car with an automatic gearbox, which automatically selects an appropriate gear to use based on the current speed:
次の例では、Car のサブクラスである AutomaticCar という新しいクラスを定義します。 AutomaticCar クラスは、現在の速度に基づいて使用する適切なギアを自動的に選択する自動ギアボックスを備えた車を表します。
class AutomaticCar: Car {
override var currentSpeed: Double {
didSet {
gear = Int(currentSpeed / 10.0) + 1
}
}
}
Whenever you set the currentSpeed property of an AutomaticCar instance, the property’s didSet observer sets the instance’s gear property to an appropriate choice of gear for the new speed. Specifically, the property observer chooses a gear that’s the new currentSpeed value divided by 10, rounded down to the nearest integer, plus 1. A speed of 35.0 produces a gear of 4:
AutomaticCar インスタンスの currentSpeed プロパティを設定すると、そのプロパティの didSet オブザーバーがインスタンスのギア プロパティを新しい速度に適したギアの選択に設定します。 具体的には、プロパティ オブザーバーは、新しい currentSpeed 値を 10 で割って最も近い整数に切り捨て、1 を加えたギアを選択します。速度 35.0 はギア 4 を生成します。
let automatic = AutomaticCar()
automatic.currentSpeed = 35.0
print("AutomaticCar: \(automatic.description)")
// AutomaticCar: traveling at 35.0 miles per hour in gear 4
Preventing Overrides
オーバーライドの防止
You can prevent a method, property, or subscript from being overridden by marking it as final. Do this by writing the final modifier before the method, property, or subscript’s introducer keyword (such as final var, final func, final class func, and final subscript).
メソッド、プロパティ、添え字を「final」としてマークすることで、オーバーライドされないようにすることができます。 これを行うには、メソッド、プロパティ、または添字の導入キーワード(final var、final func、final class func、final subscript など)の前に、final 修飾子を記述します。
Any attempt to override a final method, property, or subscript in a subclass is reported as a compile-time error. Methods, properties, or subscripts that you add to a class in an extension can also be marked as final within the extension’s definition. For more information, see Extensions.
サブクラス内の最終メソッド、プロパティ、またはサブスクリプトをオーバーライドしようとすると、コンパイル時エラーとして報告されます。 拡張機能内のクラスに追加するメソッド、プロパティ、または添字は、拡張機能の定義内で final としてマークすることもできます。 詳細については、「拡張機能」をご覧ください。
You can mark an entire class as final by writing the final modifier before the class keyword in its class definition (final class). Any attempt to subclass a final class is reported as a compile-time error.
クラス定義(final class)のクラスキーワードの前にfinal修飾子を記述することで、クラス全体をfinalとしてマークできます。 最終クラスをサブクラス化しようとすると、コンパイル時エラーとして報告されます。
