プロトコルは、他のプロトコルを 1 つ以上継承することができ、継承した要件に加えてさらに要件を追加することができます。プロトコル継承のシンタックスは、クラス継承のシンタックスに似ていますが、複数の継承するプロトコルをカンマ区切りで列挙することができます。

protocol InheritingProtocol: SomeProtocol, AnotherProtocol {
    // プロトコル定義
}

次は、TextRepresentable プロトコルを継承するプロトコルの例です。

protocol PrettyTextRepresentable: TextRepresentable {
    var prettyTextualDescription: String { get }
}

この例では、TextRepresentable を継承する新しいプロトコル PrettyTextRepresentable を定義しています。PrettyTextRepresentable を採用する場合、TextRepresentable に強制される追加要件に加えて、PrettyTextRepresentable に強制される追加要件をすべて満たす必要があります。この例では、String を返す gettable プロパティ prettyTextualDescription の要件を PrettyTextRepresentable が追加しています。

PrettyTextRepresentable を採用し準拠するよう、SnakesAndLadders クラスを拡張することができます。

extension SnakesAndLadders: PrettyTextRepresentable {
    var prettyTextualDescription: String {
        var output = textualDescription + ":\n"
        for index in 1...finalSquare {
            switch board[index] {
            case let ladder where ladder > 0:
                output += "▲ "
            case let snake where snake < 0:
                output += "▼ "
            default:
                output += "○ "
            }
        }
        return output
    }
}

このエクステンションは、PrettyTextRepresentable プロトコルを採用し、SnakesAndLadders 型の prettyTextualDescription プロパティの実装を提供することを示しています。PrettyTextRepresentableである何かは、TextRepresentable でもあるため、prettyTextualDescription の実装のはじめに TextRepresentable からの textualDescription プロパティにアクセスし、出力する文字列の先頭にしています。 コロンと改行を追加し、整形テキスト表現の先頭としてこれを使用しています。そして、ボードのマス配列内を繰り返し処理し、各マスの内容を表現する幾何学形状を追加します。

  • マスの値が 0 より大きい場合は、梯子のベースで  で表現します。
  • マスの値が 0 より小さい場合は、蛇の頭で  で表現します。
  • その他はマスの値は 0 で、フリーのマスで  で表現します。

SnakesAndLadders インスタンスの説明を整形テキストで出力するために、prettyTextualDescription プロパティを使用することができます。

print(game.prettyTextualDescription)
// A game of Snakes and Ladders with 25 squares:
// ○ ○ ▲ ○ ○ ▲ ○ ○ ▲ ▲ ○ ○ ○ ▼ ○ ○ ○ ○ ▼ ○ ○ ▼ ○ ▼ ○

Portions of this page are translations based on work created and shared by Apple and used according to terms described in the Creative Commons Attribution 4.0 International License.