LoginSignup
1
3

More than 5 years have passed since last update.

Swiftのenumが便利

Posted at

enum使っていますか?
Swiftの列挙型は単なる整数型の集合ではなく、型を指定したり独自のメソッドを定義できたりと便利なものになっています。

メソッドを定義

Swiftの列挙型にはメソッドを定義することができます。

enum Direction {
    case up, down, right, left

    func reverse() -> Direction {
        switch self {
        case .up:
            return .down
        case .down:
            return .up
        case .right:
            return .left
        case .left:
            return .right
        }
    }
}

let up = Direction.up
up.reverse() // down

let right = Direction.right
right.reverse() // left

独自イニシャライザ

rawValueによる初期化だけでなく独自のイニシャライザを定義できます。

enum Animal {
    case dog, cat

    init?(name: String) {
        switch name {
        case "犬":
            self = .dog
        case "猫":
            self = .cat
        default:
            return nil
        }
    }
}

let dog = Animal(name: "犬") // dog
let hoge = Animal(name: "hoge") // nil

共用型の列挙型

シンプルな列挙型と、複数の異なるタプルの構造を併せ持つことができる列挙型を共用型の列挙型と言います。
下記の例では、"custom"に文字列型を付加しています。

enum Message {
    case foo
    case bar
    case custom(String)

    func string() -> String {
        switch self {
        case .foo:
            return "foo"
        case .bar:
            return "bar"
        case .custom(let s):
            return s
        }
    }
}

let foo = Message.foo
foo.string() // foo

let custom = Message.custom("hoge")
custom.string() // hoge

なお、共用型の列挙型では==演算子を独自に定義しないと値の比較ができません。
以下サンプルです。

static func ==(v1: Message, v2: Message) -> Bool {
    switch (v1, v2) {
    case (.foo, .foo):
        return true
    case (.bar, .bar):
        return true
    case (.custom(let s1), .custom(let s2)):
        return s1 == s2
    default:
        return false
    }
}

Message.custom("aaa") == Message.custom("bbb") // false
Message.custom("aaa") == Message.custom("aaa") // true
1
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3