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

Swift Goodies: Ideas for Cascading ‘if’ Clauses

Swift 1.2 has brought the ability to cascade let and logic within the scope of one if statement – this is huge and will be widely used. However, what’s missing is some concept of how to style them.

In much of the Apple code, one sees them cascaded on one line, then after 80 characters or so a continuation on the second line:

if let foo = x as? String, a = b(), let c = y as Int where c > blahBlah, more, and more, and more {

with the beginning ‘{‘ brace at the end.

Personally, I find this hard to read, and its hard to visually find the beginning brace on these multi-line statements.

I thought about:

if
    let foo = x as? String,
    let c = y as Int where c > blahBlah,
    more,
    and more
{


which is easy to type - hit the tab key after typing 'if' and then Xcode autoindents the rest for you. This is similar to a style I often used in large 'C' (or Objective C) if statements.

However, there would seem to be reluctance to wasting a whole line with 'if', so what I'm doing is typing 'if' followed by a tab followed by the first clause:

if  let foo = x as? String,
    let c = y as Int where c > blahBlah,
    more,
    and more
{


I'm fairly happy with this, and when I need to convert a single clause if to have multiple clauses, I then add a the tap in front of the first clause, and a new line + backspace in front of the '{' char.

You may not like either of the above styles, but its worth thinking about what style you do like, and then consistently apply it as you write your code.