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

Jeremy Pereira jeremy.j.pereira at googlemail.com
Thu Apr 7 10:02:11 CDT 2016


> On 7 Apr 2016, at 14:17, Brent Royal-Gordon <brent at architechies.com> wrote:
> 
>> 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.

Having read your email, I’m pretty sure I do, and my problem with it remains.

> 
> 
> `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() {} 
> 	} 


It’s not _really_ strange. The type of new cannot be known at compile time, only that it is some subclass of Foo (or Foo itself of course).

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

Is it more readable? Has anybody done any objective testing?

> * `Self` will be allowed in member bodies. This will allow you to write that `new` line as:
> 
> 		let new: Self = Self()

And that is certainly not more readable than the line it replaces. The line it replaces tells me explicitly that I am creating a new object of the same type as self. This does not. The casual reader might easily assume that you will get an object of type Foo. 


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

I’m not wild about that either (especially as my autocomplete seems to go for the type before the variable every time) and if you used a variable called `string` in the same context as a lot of static methods on `String` it would suffer from the same problem that I am concerned about wrt readability.


> 



More information about the swift-evolution mailing list