Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'case' inside a switch statement negative indented? [duplicate]

I don't think this is entirely a Swift / Xcode thing, as I've seen it in other languages / IDEs as well.

Why is 'case' inside a switch statement negative indented (I'm not sure if that's the correct way of wording that)?

I would expect a Switch statement to look something like this

switch(type) {
    case 1:
        // do something
    break;
    case 2:
        // do something else
    break;
    default:
        // default
    break;
}

But Xcode insists on this

switch(type) {
case 1:
    // do something
    break;
case 2:
    // do something else
    break;
default:
    // default
    break;
}

Is this a bug, or is there a reason for this? If so, what is it? It's something that has bugged me for quite some time.

like image 396
Luke Berry Avatar asked Oct 13 '15 17:10

Luke Berry


People also ask

What is not allowed in a switch statement?

The switch statement doesn't accept arguments of type long, float, double,boolean or any object besides String.

What happens in a switch statement?

The switch statement evaluates an expression, matching the expression's value against a series of case clauses, and executes statements after the first case clause with a matching value, until a break statement is encountered.

Can we write 2 defaults in switch-case?

There can be at most one default statement. The default statement doesn't have to come at the end. It may appear anywhere in the body of the switch statement. A case or default label can only appear inside a switch statement.

Do you need braces in switch-case?

The braces are always needed following the switch statement. No braces are needed following any case. If the variable is equal to one of the values following a case, then the code following the case is executed.


1 Answers

Well, I would guess that the break statement belongs to the "section" in the case clause. And as any other statement, it is indented relative to the case. As for the case relative to switch - well I don't know.

But I'm completely with you - and formatting is a matter of personal preference anyway. Since the formatting rules in Xcode are not explicitly defined - it cannot be a bug ;)

FWIW, I prefere this style

switch x {
    case 1:
        // do something
        break
    case 2:
        // do something else
        break
    default:
        // default
        break
}
like image 82
CouchDeveloper Avatar answered Oct 31 '22 19:10

CouchDeveloper