Inheritance 継承

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. クラスは、メソッド、プロパティ、および他の特徴を別のクラスから継承することができます。あるクラスが他のものから継承するとき、継承を受けているクラスはサブクラスとして知られています、そして、そこからそれが譲り受ける原点のクラスは、それのスーパークラスとして知られています。継承は、スウィフトにおいてクラスを他の型と区別する基本的挙動です。

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. スウィフトのクラスは、それらのスーパークラスに属しているメソッド、プロパティ、そして添え字の呼び出しやアクセスが行えて、それらのメソッド、プロパティ、そして添え字の独自の優先的に使われる改変板を提供することでそれらの挙動の洗練や修正を行えます。スウィフトは、あなたの無効化が正しいものであることを、その無効化定義がスーパークラス定義に合致するのを確認することによって確実にします。

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. スウィフトのクラスそれらは、ひとつの共通の基盤クラスから継承はしません。スーパークラスを指定することなくあなたが定義するクラスは、自動的に基盤クラスになり、あなたが基礎とするために使えます。

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のサブクラスによって目的に合わせて作り変えられます:

  1. class Vehicle {
  2. var currentSpeed = 0.0
  3. var description: String {
  4. return "traveling at \(currentSpeed) miles per hour"
  5. }
  6. func makeNoise() {
  7. // do nothing - an arbitrary vehicle doesn't necessarily make a noise(何もしない - ある任意の乗り物が必ず音を出すわけではない)
  8. }
  9. }

You create a new instance of Vehicle with initializer syntax, which is written as a type name followed by empty parentheses: あなたは、Vehicleの新しいインスタンスを初期化構文を使って作成します、それは1つの型名に続く空の丸括弧として書かれます:

  1. 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プロパティにアクセスして、その乗り物の現在速度の説明を人の読めるように出力することが出来ます:

  1. print("Vehicle: \(someVehicle.description)")
  2. // Vehicle: traveling at 0.0 miles per hour(Vehicle: 時速0.0マイルで運行中)

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: あるサブクラスがあるスーパークラスを持つことを表わすには、サブクラスの名前をスーパークラスの名前の前に、コロンで区切って書きます:

  1. class SomeSubclass: SomeSuperclass {
  2. // subclass definition goes here(サブクラス定義がここに来ます)
  3. }

The following example defines a subclass called Bicycle, with a superclass of Vehicle: 以下の例は、Vehicleのスーパークラスを持つ、Bicycleと呼ばれるサブクラスを定義します:

  1. class Bicycle: Vehicle {
  2. var hasBasket = false
  3. }

The new Bicycle class automatically gains all of the characteristics of Vehicle, such as its currentSpeed and description properties and its makeNoise() method. この新しいBicycleクラスは、自動的にVehicleのすべての特徴を獲得します、例えばそれのcurrentSpeedおよびdescriptionプロパティやそれのmakeNoise()メソッドなど。

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インスタンスは、入れ物かごを持ちません。あなたは、特定のBicycleインスタンスに対してhasBasketプロパティをtrueに設定することが、そのインスタンスを作成した後で行えます:

  1. let bicycle = Bicycle()
  2. 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プロパティについて問い合わせることが出来ます:

  1. bicycle.currentSpeed = 15.0
  2. print("Bicycle: \(bicycle.description)")
  3. // Bicycle: traveling at 15.0 miles per hour(自転車:時速15マイルで運行中)

Subclasses can themselves be subclassed. The next example creates a subclass of Bicycle for a two-seater bicycle known as a “tandem”: サブクラスは、それ自身サブクラスを作られることが出来ます。次の例は、「タンデム」として知られる2座席自転車のために、Bicycleのサブクラスを作成します:

  1. class Tandem: Bicycle {
  2. var currentNumberOfPassengers = 0
  3. }

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から継承します、そして今度はそれがすべてのプロパティとメソッドを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から継承する読み込み専用のdescriptionプロパティについて問い合わせることができます:

  1. let tandem = Tandem()
  2. tandem.hasBasket = true
  3. tandem.currentNumberOfPassengers = 2
  4. tandem.currentSpeed = 22.0
  5. print("Tandem: \(tandem.description)")
  6. // Tandem: traveling at 22.0 miles per hour(2人乗り:時速22.0マイルで運行中)

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つ)が、そのオーバーライドのためにあなたが提供するものと合致する宣言を持っていることを確認するように、スウィフトのコンパイラを促します。この調査は、あなたのオーバーライドの定義が正しいことを確実にします。

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 of someMethod() by calling super.someMethod() within the overriding method implementation. someMethod()という名前のオーバーライドされたメソッドは、オーバーライドしているメソッド実装内でsuper.someMethod()を呼ぶことによって、スーパークラス版のsomeMethod()を呼ぶことができます。
  • An overridden property called someProperty can access the superclass version of someProperty as super.someProperty within the overriding getter or setter implementation. somePropertyと呼ばれるオーバーライドされたプロパティは、オーバーライドしているゲッターまたはセッター実装内で、super.somePropertyのようにしてスーパークラス版のsomePropertyにアクセスすることができます。
  • An overridden subscript for someIndex can access the superclass version of the same subscript as super[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の新しいサブクラスを定義します、それは、TrainVehicleから受け継ぐmakeNoise()メソッドをオーバーライドします:

  1. class Train: Vehicle {
  2. override func makeNoise() {
  3. print("Choo Choo")
  4. }
  5. }

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メソッドが呼び出されるのを見ることができます。

  1. let train = Train()
  2. train.makeNoise()
  3. // 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: 以下の例は、Carと呼ばれる新しいクラスを定義します、それは、Vehicleのサブクラスです。Carクラスは、gearと呼ばれる、1の省略時の値を持つ、新しい格納プロパティを導入します。Carクラスはまた、それがVehicleから継承するdescriptionプロパティをオーバーライドして、現在のギアーを示すあつらえの説明を提供します:

  1. class Car: Vehicle {
  2. var gear = 1
  3. override var description: String {
  4. return super.description + " in gear \(gear)"
  5. }
  6. }

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クラス版のdescriptionは、それからこの説明の最後に現在のギアーについての情報を提供するために追加のテキストを加えられます。

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クラスのインスタンスを作成して、それのgearcurrentSpeedプロパティを設定するならば、あなたはそれのdescriptionプロパティがCarクラス内で定義される特注の説明を返すのを見ることができます:

  1. let car = Car()
  2. car.currentSpeed = 25.0
  3. car.gear = 3
  4. print("Car: \(car.description)")
  5. // Car: traveling at 25.0 miles per hour in gear 3(Car: 3速ギアで時速25.0マイルで運行中)

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: 以下の例はAutomaticCarと呼ばれる新しいクラスを定義します、それは、Carのサブクラスです。AutomaticCarクラスはオートマチック・ギアボックスをもつ車を表します、それは、現在の速度に基づいて自動的に使用するのに適切なギアを選びます。

  1. class AutomaticCar: Car {
  2. override var currentSpeed: Double {
  3. didSet {
  4. gear = Int(currentSpeed / 10.0) + 1
  5. }
  6. }
  7. }

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オブザーバーは、そのインスタンスのgearプロパティを新しい速度のために適切な選択に設定します。具体的には、プロパティオブザーバーは、新しいcurrentSpeed値を10で割って、最も近い整数に丸めて、1を加えたギアを選びます。速度35.0はギア4を示します:

  1. let automatic = AutomaticCar()
  2. automatic.currentSpeed = 35.0
  3. print("AutomaticCar: \(automatic.description)")
  4. // AutomaticCar: traveling at 35.0 miles per hour in gear 4(AutomaticCar: 時速35.0マイル、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修飾子を書くことによって、これをしてください(例えば、final varfinal funcfinal class func、そしてfinal subscriptなど)。

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. あるサブクラスの中の最終的なメソッド、プロパティ、または添え字をオーバーライドするどんな試みも、コンパイル時エラーとして報告されます。あなたがある拡張においてクラスに加えるメソッド、プロパティ、または添え字は、また、拡張の定義内で最終版として印されることができます。

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. あなたは、そのクラス定義においてclassキーワードの前にfinal修飾子を書くことによって(final class)、そのクラス全体を最終版として印することができます。最終版クラスにサブクラスを作る試みは何であれ、コンパイル時エラーを報告します。

Subscripts 添え字

Initialization 初期化