LoginSignup
3
2

More than 5 years have passed since last update.

SwiftとObjective-CのEnumの違い

Last updated at Posted at 2016-08-10

SwiftとObjective-CのEnumの違いについて調べました

Objective-Cの書き方

Objective-Cだとこんな感じ

Objective-C

typedef NS_ENUM(NSUInteger,Zoo) {
    Monkey = 0,
    Gorilla,
    Chimpanzee,
};

以上。

Swiftの書き方

Swiftだと色々な書き方ができます
基本的な書き方は以下のような感じです

enum Zoo : Int {    
    case Monkey = 0
    case Gorilla
    case Chimpanzee
} 

数値以外のデータを列挙したものに入れることができます。

enum Zoo : String { 
    case Monkey = "サル"
    case Gorilla = "ゴリラ"
    case Chimpanzee = "チンパンジー"
} 

関数も定義できます

enum Zoo {  
    case Monkey
    case Gorilla
    case Chimpanzee

    func zooType() -> String {
        switch self
        case .Monkey :
        return "サル"
        case .Gorilla :
        return "ゴリラ"
        case .Chimpanzee :
        return "チンパンジー"
    }
} 

値に引数を与えることもできます

enum Zoo {
    case Monkey(String,String)
}

値に引数を与えた場合、switch文で分ける必要があります
switch文以外のところで分ける記述を書いても分けることができないので注意

var cage = Zoo.Monkey("サル","チンパンジー")

 switch cage {
        case .Monkey(let monkey, let tinpanzi):
            print(monkey) //サル
            print(tinpanzi) //チンパンジー
            break
        }

まとめ

SwiftのEnumは、Objective-CのEnumより列挙できるものが多い
SwiftのEnumはいいぞ。

3
2
0

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