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

Brent Royal-Gordon brent at architechies.com
Thu Apr 7 07:17:40 CDT 2016


> As I understand it, the proposal is that `Self` can be used as an alias to `self.dynamicType`, which is an object in the sense of entity in Swift but not an instance of a class or struct. 

You don't understand it correctly.

Currently, `Self` in a class definition means "whatever subclass this object happens to be". So if you say this:

	class Parent {
		func foo() -> Self
	}
	class Child: Parent {}

Then on `Child`, the `foo()` function returns `Self`.

`Self` isn't supported in value types because, since you can't subclass value types, it always means exactly the same thing as writing the type's name. `Self` also isn't supported in the bodies of class members because, when you call members on it, it's equivalent to `self.dynamicType`. This is actually really strange, though, because it means that you can't actually write certain types explicitly. For instance:

	class Foo { 
	    func foo() -> Self { 
	        let new = self.dynamicType.init()
	        // `new` is of type Self, but you can't actually write `let new: Self`
	        return new 
	    } 
	    required init() {} 
	} 

What this proposal is saying is:

* `Self` will be allowed in value types. It will always mean the same thing as writing the type's name explicitly, but that's okay; it's more readable.
* `Self` will be allowed in member bodies. This will allow you to write that `new` line as:

		let new: Self = Self()

Oh, and `#Self` will also be permitted, which is always literally just a shorthand for whatever type you happen to be in right now.

> My point, though is not the exact semantics of what you call the thing that `Self` is but that having it and `self` in the same code will lead to readability issues because you can have `self` and `Self` in the same code referring to completely different things and they only differ in the case of the first letter.

People seem to be okay with things like `var string: String`; having `self` be of type `Self` is no different.

* * *

Having said all this, now that we have `#Self`, I'm wondering if we still want `Self` in value types. The two are *exactly* equivalent in value types as far as I can tell, and `Self` in classes implies dynamic behavior which is not supported by value types. The use of `Self` in class member bodies is a clean win, the existence of `#Self` is a clean win, but I'm not sure we need the value type thing too.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list