Swift Goodies: Using Enums for View/Segment Identification

One technique I used in Objective C to make my code clearer was using enums to map my ‘view with tag’ or ‘segment index’ to something besides a number.

That is, given a table view cell with 4 ‘tagged’ views, instead of writing:

switch (sender.tag) {
case 1:
...

I’d use an anonymous enum:

static enum { 
    NameTextField=1, EnableSwitch
};

switch(sender.tag) {
case NameTextField:
    ...
    break;
case EnableSwitch:
    ...
    break;
//default: // Not needed if you added a case for each enum value
}

In Swift, you can do the same, and even better, your enums can be namespaced (meaning, you can use ‘Email’ in more than one)

private enum Segments: Int {
    case Name = 1, Email
}

@IBAction segmentedAction(sender: UISegmentedControl) {
let selectedSegment = Segments(rawValue: sender.selectedSegmentIndex)!
switch selectedSegment {
case .Name:
    ...
case .Email:
    ...
//default: () // Not needed if you add a case for each enum value
}

When I go back and look at old code, these strings greatly improve the speed at which you can understand what the code is suppose to do.

Advertisements

One thought on “Swift Goodies: Using Enums for View/Segment Identification

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s