エクステンションで、既存のクラスや構造体、列挙型に新しいネストされた型を追加することができます。
extension Int {
enum Kind {
case Negative, Zero, Positive
}
var kind: Kind {
switch self {
case 0:
return .Zero
case let x where x > 0:
return .Positive
default:
return .Negative
}
}
}
この例では、Int
に新しいネストされた列挙型を追加しています。この列挙型 Kind
は、特定の数値が表す数の種類を表現しています。具体的には、数値がマイナスか、ゼロか、プラスかを表現しています。
また、この例では Int
に、その整数に適切な Kind
の列挙型ケースを返す、新しいコンピューテッドのインスタンスプロパティ Kind
を追加しています。
どの Int
値ででも、ネストされた列挙型を利用することができます。
func printIntegerKinds(numbers: [Int]) {
for number in numbers {
switch number.kind {
case .Negative:
print("- ", terminator: "")
case .Zero:
print("0 ", terminator: "")
case .Positive:
print("+ ", terminator: "")
}
}
print("")
}
printIntegerKinds([3, 19, -27, 0, -6, 0, 7])
// "+ + - 0 - 0 +" と出力
この関数 printIntegerKinds
は、Int
値の配列を入力に取り、次々に値を繰り返し処理します。配列の各整数値に対して、関数でコンピューテッドプロパティ Kind
が適用され、適切な説明を出力しています。
NOTE
number.kind
は、Int.Kind
型であるとわかっています。そのため、switch
文にあるすべての Int.Kind
のケースを、Int.Kind.Negative
ではなく、.Negative
のように簡略形式で記述することができます。
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.