[swift-evolution] class indent in swift, history?

Will Stanton willstanton1 at yahoo.com
Tue Mar 7 00:42:05 CST 2017


Hello Chris and perhaps core team members,

The comments on tab-levels for `switch` made me want to ask about the considerations that went into class and protocol-level indentation.

Sorry if my wording isn’t precise, but in Objective-C, functions can (should) be at the same 0-indent level as the class:
@implementation Foo
// No indent!
- (void)doSomething {
}
@end

However, in Swift, method and nested types are indented by default:
class Foo : Bar {
	// Things indented!
	enum Types {
	}
	func doSomething() {
	}
}


Was the change mostly driven by the desire for protocol+class+struct+enum consistency in ‘increasing’ the scope+indent level? Were there other considerations?
Why didn’t the language evolve into something like this to reduce the use of horizontal whitespace, allowing class functions/types at the root/top level? Like:
@class Foo : Bar
enum Types {
}
func doSomething() {
}
@end


Regards,
Will Stanton

> On Mar 7, 2017, at 12:52 AM, Chris Lattner via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I can understand how you might find this unnerving, but it is important to understand that Swift and Objective-C/C have different semantics when it comes to case labels:  in Swift, a case label *is* a scope, and *is* part of the switch statement.  In Objective-C, a case label is just a label, like any other goto label: it is not a scope and is not necessarily a direct child of the switch statement.
> 
> C and Objective-C’s behavior is what leads to obscure but important things like Duff’s device (https://en.wikipedia.org/wiki/Duff's_device).  
> 
> In contrast, Swift fixes the scoping, fallthrough, and other related problems all in one fell swoop, and ensures that cases are directly nested under the switch (unlike in C, where they can be nested under other statements within the switch).  Because the case/default labels are *part of* the switch in Swift, it makes sense for them to be indented at the same level.
> 
> While I can respect that you aesthetically have a preference for the Objective-C way of doing things, the rationale for this behavior change wasn’t arbitrary and wasn’t due to "LLVM style".  It is an important reflection of the core semantics of the language model.
> 
> Finally, conservation of horizontal whitespace is important for comprehension of code, particularly w.r.t. readability and maintenance.  This is why statements like guard exist: to reduce nesting and indentation, directing the attention of someone reading and maintaining code to the important parts.
> 



More information about the swift-evolution mailing list