- Proposal: SE-XXXX
- Author(s): Erica Sadun
- Status: TBD
- Review manager: TBD
This proposal introduces Self
, an equivalent to self.dynamicType
. It extends the use of Self
from protocols and class method results to value types and into the bodies of class members.
This proposal was discussed on the Swift Evolution list in the [Pitch] Adding a Self type name shortcut for static member access thread.
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
andTypeName.classMember
may not be synonyms in class types with non-final members.
Joe Groff points out that Self
inside a class scope already means "the dynamic class of self
", not "the type this declaration statically appears within." He writes, "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"
In this proposal, Self
equates 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."
A further literal, #Self
expands to the static type of the code it is
declared within. This is always the same as Self
unless you're coding
in a class. #Self
will offer a literal textual replacement just like #file
, etc.
Not at this time
Thanks Sean Heber, Lily Ballard, Joe Groff, Timothy Wood, Brent Royal-Gordon, Andrey Tarantsov, Austin Zheng