1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

排他的なパラメータを表現するのにenumが便利だった話

Posted at

初めに

2つの引数を取る関数があって、引数のどちらか片方だけnilでないようにしたい、というとき ↓

func handleValue(a: Int?, b: Double?) {
    assert((a == nil) != (b == nil))
    
    // 実際の処理
}

こんな感じでassertを使えば実現は出来るが、enumを使えばより綺麗に書けることを知った。
そもそも関数を分けろ、などの設計の話はここでは無視する。

やったこと

こんなenumを定義し、

enum Value {
    case a(intValue: Int)
    case b(doubleValue: Double)
}

関数をこう変える

func handleValue(value: Value) {
    switch value {
        case let .a(intValue):
            // aのときの処理
        case let .b(doubleValue):
            // bのときの処理
    }
}

これで、assertを付けなくてもやりたいことが実現できる上にinterfaceとして排他的なことが明示できるので何かと都合が良い。

終わりに

enumはいろいろと使い方が難しいが、慣れると便利だ。

1
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?