Sam Fischer Sam Fischer - 2 months ago 10
Swift Question

How to associate multiple values with enums in Swift?

I'm trying to use an enum to categorize the various sections in a


Here's the current implementation of the Section

enum Section: Int, CustomStringConvertible {

case open = 0
case closed = 1

var description: String {
switch self {
case .open:
return "Open"
case .closed:
return "Closed"

Here's how I'm using it to name the titles for the headers in my
sections :

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return Section(rawValue: section)?.description

I'm just curious to know if there's a better way of implementing this. Perhaps with tuples. I'm not exactly sure, but I'd love to see if there's a better solution.

This is just one use case and the two cases given are just for brevity. I'd like to use multiple values, for instance
associated with the given


If all you're trying to do is set up a correspondence between numbers and strings:

0 -> Open
1 -> Closed

... then it's hard to see what the enum is for. What you want is a dictionary where the numbers are keys, or even just a simple array:

let arr = ["Open", "Closed"]

In the array, the string is indexed by the numbers:

return arr[rawValue: section]