Sam Fischer Sam Fischer - 1 month ago 6
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

UITableView
.

Here's the current implementation of the Section
enum
:

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
UITableView
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
UIColors
associated with the given
case
.

Answer

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]