[swift-evolution] Pre proposal: Should there be a way to distinguish class instances from struct instances
dabrahams at apple.com
Thu Dec 17 15:33:31 CST 2015
> On Dec 17, 2015, at 4:23 AM, Daniel Steinberg via swift-evolution <swift-evolution at swift.org> wrote:
> The way in which we reason about instances of value types and instances of reference types is significantly different and yet there is no way to easily distinguish them in Swift.
> In Objective-C, for example, if we have an NSDate and an NSTimeInterval we can tell that NSDate is a reference type and NSTimeInterval is a value type by looking at how it is used in code
> NSDate *myDate = //…
> NSTimeInterval someTimeInterval = //…
> The “*” helps us see that myDate is a pointer to an instance of NSDate.
> We see this in methods that return values as well
> - (NSString *)aStrringReturningMethod // …
> - (NSInteger)numberOfMistakesInThisEmail //...
> I realize that this is a result of Objective-C living in C’s world and we don’t have that constraint in Swift.
> However, this means that when the semantics of variables, parameters, properties, and return values from methods is not always clear in our code. Because structs can have methods in Swift it is all to easy to confuse an instance of a struct with an instance of a class.
> I may be alone here, but I think it would be less confusing if there were some way to distinguish between value types and reference types in code.
The real differences happen whenever you mutate them by part (assignment acts the same), which suggests that they should have different syntax for member access, e.g. someObject->mutatingMethod() vs. someValue.mutatingMethod().
Personally, I like that sort of thing. Not to discourage you, but I think most people don’t recognize that types with value semantics are fundamentally different from those with reference semantics, e.g. avoiding a syntactic barrier between them was an explicit design goal of Swift 1. Also I don’t think you’d find much support for even a 1-character penalty on method calls and property accesses to classes. So, while I think we ought to do something in this direction, I expect it to be hard-won.
More information about the swift-evolution