LoginSignup
35
32

More than 5 years have passed since last update.

[Swift] 列挙型の作りが面白い

Last updated at Posted at 2014-06-29

Swfitの列挙型が面白いです。

C#のように数値が割り当てられない代わりに
列挙型に関数が作れます。いろいろ応用が効きそうです。

enum CompassPoint {
    case North
    case South
    case East
    case West

    // 各列挙値に対して文字列で返す
    func toString () -> String {
        switch self{
            case CompassPoint.North:
                return "北"
            case CompassPoint.South:
                return "南"
            case CompassPoint.East:
                return "東"
            case CompassPoint.West:
                return "西"
            default :
                return ""
        }
    }

    // ボタン押下アクション
    @IBAction func ButtonClick(sender : UIButton) {
        hoge(CompassPoint.West)
    }

    // 文字列で表示
    func hoge(key:CompassPoint){
        println(key.toString())
    }

}

ただし。上記のように値を返すだけであれば関数不要です。
自由な型で返せるのがすばらしい。

    enum CompassPointA : String {
        case North = "北"
        case South = "南"
        case East = "東"
        case West = "西"
    }

    // ボタン押下アクション
    // toRawを忘れずに。
    @IBAction func ButtonClick(sender : UIButton) {
        println(CompassPointA.North.toRaw())
    }

35
32
4

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
35
32