[swift-evolution] [Pitch] Adding a Self type name shortcut for static member access

Joe Groff jgroff at apple.com
Tue Apr 5 17:04:36 CDT 2016


> On Apr 5, 2016, at 3:02 PM, Erica Sadun <erica at ericasadun.com> wrote:
> 
> As the discussion seems to be quieting down, I've tried to summarize the on-list discussion and distill it into a preliminary proposal draft. Please let me know if this covers what you think it should or if I've entirely missed the mark. (It wouldn't be the first time.)
> 
> Regards,  -- Erica
> 
> Adding a #Self literal to Swift
> 
> 	• Proposal: SE-XXXX
> 	• Author(s): Erica Sadun
> 	• Status: TBD
> 	• Review manager: TBD
> Introduction
> 
> This proposal introduces #Self, a new literal that expands to self.dynamicType.
> 
> This proposal was discussed on the Swift Evolution list in the [Pitch] Adding a Self type name shortcut for static member access thread.
> 
> Motivation
> 
> It is common in Swift to reference an instance's type, whether for accessing a static member or passing a type for an unsafe bitcast, among other uses. At this time, you can either fully specify a type by name or use self.dynamicType to access an instance's dynamic runtime type as a value. 
> 
> struct MyStruct {
>     static func staticMethod() { ... }
>     func instanceMethod() {
>         MyStruct.staticMethod()
>         self.dynamicType.staticMethod()
>     }
> }
> 
> 	• As type names grow large, readability suffers, for example MyExtremelyLargeTypeName.staticMember
> 	• Code using hardwired type names is less portable than code that automatically knows its type.
> 	• Renaming a type means updating any TypeName references in code.
> 	• Using self.dynamicType fights against Swift's goals of concision and clarity; it is both noisy and esoteric.
> 	• self.dynamicType.classMember and TypeName.classMember may not be synonyms in class types with non-final members.
> 	• Joe Groff points out, Self inside a class scope already means "the dynamic class of 'self'", not "the type this declaration statically appears within...Swift ought to allow developers to utter Self in the bodies of class methods. It would be consistent to extend that courtesy to value types, where dynamic Self always matches the static type, from that principle"
> Detail Design
> 
> In this proposal, #Self expands to the dynamic type of self and only the dynamic type of self. Joe Groff writes, "I don't think it's all that onerous to have to write ClassName.foo if that's really what you specifically mean."

What you're describing should be spelled `Self`, IMO. I think Tim intended `#Self` to mean the *static* type the code is declared inside (which is the same as Self unless you're in a class).

-Joe

> Alternatives Considered
> 
> Not at this time
> 
> Acknowlegements
> 
> Thanks Sean Heber, Kevin Ballard, Joe Groff, Timothy Wood, Brent Royal-Gordon, Andrey Tarantsov, Austin Zheng



More information about the swift-evolution mailing list