Skip to content

Instantly share code, notes, and snippets.

@erica
Last active December 11, 2018 01:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erica/c60c7d51809889f3dfd47cdb482d6227 to your computer and use it in GitHub Desktop.
Save erica/c60c7d51809889f3dfd47cdb482d6227 to your computer and use it in GitHub Desktop.

Expanding Swift Self to methods and value types

Introduction

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.

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 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"

Detail Design

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.

Alternatives Considered

Not at this time

Acknowlegements

Thanks Sean Heber, Lily Ballard, Joe Groff, Timothy Wood, Brent Royal-Gordon, Andrey Tarantsov, Austin Zheng

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment