2017-06-02 47 views
0

我試圖完成一個任務,它傳遞一個整數值枚舉,並返回一個特定的字符串傳入的integrer。通過INT枚舉並返回一個字符串

我使用枚舉,因爲整數是已知的,每個都有一個含義。我也做了以下情況:

enum Genre: String { 
    case 28 = "Action" 
    case 12 = "Adventure" 
    case 16 = "Animation" 
    case 35 = "Comedy" 
    case 80 = "Crime" 
} 

我很期待:傳遞的情形之一時,我想返回字符串關聯。

如果您有任何問題或需要更多信息,請在評論中提問。

+0

有什麼理由不使用字典? –

+0

不,對於在這裏使用它的最佳實踐有什麼想法? – MEnnabah

+0

@MEnnabah更好的你去字典 –

回答

1

這個怎麼樣

enum Genre: Int { 
    case action = 28 
    case adventure = 12 
    case animation = 16 
    case comedy = 35 
    case crime = 80 
} 

而且使用這樣的

// enum as string 
let enumName = "\(Genre.action)" // `action` 

// enum as int value 
let enumValue = Genre.action.rawValue // 28 

// enum from int 
let action = Genre.init(rawValue: 28) 

希望它能幫助。謝謝。

1

我建議創建一個實現所需映射的字典,併爲您的密鑰創建常量以使用它們。

您可以通過創建一個名爲Constants類,並把它下面的常量開始:

static let action = 28 
static let adventure = 12 
// ... The rest of your constants. 

// Then create a dictionary that contains the values: 
static let genre = [action : "Action", adventure : "Adventure"] // And so on for the rest of your keys. 

然後,你可以訪問你需要使用字典,像這樣的任何值:

let actionString = Constants.genre[Constants.action] 

希望這有助於。

1
let Genre = [28:"action", 
12: "adventure", 
16: "animation", 
35: "comedy", 
80: "crime"] 

使用例:
let retValue = Genre[28]//"action"

這裏是操場演示:

enter image description here

1

我們不能有Intenum case名。
試試這個:

enum Genre: Int { 
case action = 28, adventure = 12, animation = 16, comedy = 35, crime = 80 

    func getString() -> String { 
    switch self { 
    case .action: return "Action" 
    case .adventure: return "Adventure" 
    case .animation: return "Animation" 
    case .comedy: return "Comedy" 
    case .crime: return "Crime" 
    } 
    } 
} 

let gener = Genre.action 
print(gener.getString())//"Action" 

如果你只知道整數值,這樣做:

let gener1 = Genre(rawValue: 12)! 
print(gener1.getString())//"Adventure"