Balbas Code

Swift の enum について

公開日: 2023-09-26 00:55:05

Swift では、enum (列挙型) を使用して、特定のグループに属する限られた値のセットを定義できます。この記事では、enum の基本的な使い方から少し高度なテクニックまでを説明します。


1. 基本的な enum


最もシンプルな形の enum です。4つの方角を表す例です:


enum Direction {
case north
case south
case east
case west
}

 


// Direction 型の変数を宣言し、.north という値を代入
let heading = Direction.north

 


2. 値を持たない enum の使用


上記の Direction 型を利用して、方向に基づく操作を switch 文で行います:


switch heading {
case .north:
print("We are heading north!") // northの場合のアクション
case .south:
print("We are heading south!") // southの場合のアクション
case .east:
print("We are heading east!") // eastの場合のアクション
case .west:
print("We are heading west!") // westの場合のアクション
}

 


3. 関連値を持つ enum


各ケースに情報を付加できる機能です。以下はバーコードを示す2つのタイプの例です:


enum Barcode {
case upc(Int, Int, Int, Int) // UPCの形式
case qrCode(String) // QRコードの形式

}

let productBarcode = Barcode.upc(8, 85909, 51226, 3)

switch productBarcode {
case .upc(let numberSystem, let manufacturer, let product, let check):
print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).") // UPCの情報を展開
case .qrCode(let productCode):
print("QR code: \(productCode).") // QRコードの情報を展開
}

 


4. 生の値を持つ enum


すべてのケースに固定の値を与えることができます。以下は惑星を示す例です:


enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune // mercuryから順に1, 2, 3...という整数値を持つ

}

// 生の値からenumのインスタンスを取得
if let possiblePlanet = Planet(rawValue: 3) {
switch possiblePlanet {
case .earth:
print("It's our home planet!") // 3はearthに対応
default:
print("Not our home planet.")
}
}

 


5. メソッドを持つ enum


enum はメソッドも持つことができます。以下は数学の操作を示す例です:


enum MathOperation {
case add, subtract

// 操作に基づいて2つの数の計算を行うメソッド
func operate(on a: Int, and b: Int) -> Int {
switch self {
case .add:
return a + b // 足し算
case .subtract:
return a - b // 引き算
}
}
}

let addition = MathOperation.add
print(addition.operate(on: 5, and: 3)) // Output: 8

 


これで Swift の enum の基本的な使い方についてのガイドは終わりです。これらのテクニックを使用して、コードをより安全で読みやすくすることができます。