[swift-evolution] Make the type-casting operator accept expressions on its right side

Joe Groff jgroff at apple.com
Thu Jan 19 12:40:52 CST 2017


> On Jan 12, 2017, at 2:50 PM, Oscar Swanros via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hello everyone. This is my first contribution to Swift Evolution. In summary: It would be nice if the type casting operator accepted expressions on its right side.
> 
> So, basically, the type casting operator only accepts types and can't process expressions on its right side.
> 
> Having a class A, and a subclass of A, B:
> 
> class A {}
> class B: A {}
> 
> And a function that returns the passed type:
> 
> func type<T: A>(t: T.Type) -> T.Type {
>     return t
> }
> 
> The following scenario works:
> 
> let b = B()
> let a = (b as A)
> 
> However the following scenario doesn't:
> 
> let b = B()
> let a = (b as type(A))
> 
> 
> 
> Having the “as” accept expressions on its right side would be really useful and could enable some truly great generic algorithm implementations.

This makes a lot of sense to support. We previously had problems that the type grammar wasn't quite a subset of the expression grammar, which prevented us from doing this before, but most of those issues have been shaken out. The last bit of weirdness is the `.self` turd that still structurally supports some of the type/expr grammar ambiguities. We have a plan to address this (SE-0090: https://github.com/apple/swift-evolution/blob/master/proposals/0090-remove-dot-self.md); that's been deferred since we don't think we can execute on it well with our current infrastructure, but that should improve with time. Once that's done, it would be naturally for the cast operators to accept an expression on their right side for dynamic type casts.

-Joe


More information about the swift-evolution mailing list