LoginSignup
1
1

More than 5 years have passed since last update.

Swiftではenumから文字列とれるのに

Posted at

Swift から Objective-C にコードを移植しているときに思ったことを...(ついでに解決策も

Swiftで文字列取得

Swift では、enumで指定したcaseの文字列が取れます

enum BloodType: String {
    case A
    case B
    case O
    case AB
}

BloodType.AB.rawValue // "AB"

あまり使わないかもしれないですが、自分は Json をパースする時などに使ってました(Jsonのenum文字列使用例に例を書いておきます)

そこで、これの Objective-C版もお願いとなり移植することに...

Objective-Cで文字列取得

とりあえず、移植してみる

typedef enum {
    A,
    B,
    O,
    AB
}BloodType;

BloodType.AB.rawValue // rawValueないよね....

ということで、取れなくて困りました
どうしようかと考えた結果、enumからindex(何番目のcaseか)はとれるので文字列を配列に入れておいて取り出すしかないかなと...

#define BloodTypeArray @"A", @"B", @"O", @"AB", nil

+ (NSString*) BloodTypeToString:(BloodType)value
{
    return [[[NSArray alloc] initWithObjects:BloodTypeArray] objectAtIndex:value];
}

// Usage
[[クラス名] BloodTypeToString:AB]; // @"AB"

配列を描くのが少し面倒ですが、1回書いてしまえば、使うのは簡単です:ok_hand:

Jsonのenum文字列使用例

Jsonでも使用例が言葉にするのが難しかったので、例を書いてしまおうとw

example.json
{
    "name":"taro",
    "blood":"AB",
    "sex":"man",
    "age":"30",
    "parent_name":{
        "father":"takeshi",
        "mother":"yuko"
    }
}

このようなJsonを解析する場合、2つenumを作るのが良いのかなと

enum Example:String {
    case name
    case blood
    case sex
    case age
    case parent_name
}

enum Parent_name:String {
    case father
    case mother
}

// Usage
let json = // Jsonを解析したDictionary
let parent_name = json[Example.parent_name.rawValue] as? Dictionary
let father = parent_name[Parent_name.father.rawValue] as? String

こんな感じで使えます!
jsonの階層をいちいち思い出さなくても良いのと、Keyとなる文字列を最初に宣言できる、Keyの追加があっても階層がわかりやすいのでどこに足すかが一目瞭然。

1
1
2

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
1