[swift-evolution] [Idea] Add dynamicType casting
Michael Henson
mikehenson at gmail.com
Fri Jan 8 22:40:46 CST 2016
Currently, the language syntax only allows type identifiers in the
type-casting-operator productions:
" " surrounds a keyword
type-casting-operator -> "is" type
type-casting-operator -> "as" type
type-casting-operator -> "as" "?" type
type-casting-operator -> "as" "!" type
The type production doesn't allow for expressions which resolve to a type,
only explicit type references.
So, if you want to refer to the item *as* its dynamic type, there's no
direct way to do that unless you declare the name of the type in code:
class Example {}
var value: Any = Example()
var again = value as value.dynamicType
// doesn't work because value.dynamicType is an expression
It should be possible to upcast to dynamicType immediately with no chance
of failure. To that end, I suggest adding two productions:
type-casting-operator -> "is" "dynamicType"
type-casting-operator -> "as" "dynamicType"
Following along the example above, we could then do:
var nowPossible = value as dynamicType
and have nowPossible be Example.Type.
Possible use cases for this functionality include:
1. Dealing with mixed-type collections from Objective-C code:
@[ @"key1", @5, @"key2", @20, @"key3", @[@"red",@"green",@"blue"]]
2. Taking advantage of type-specific polymorphism without having to modify
code:
func handleObject(obj: NSNumber) { print("Number") }
func handleObject(obj: NSData) { print("Data") }
func dispatchToHandler(kind: AnyObject) {
print("dispatching \(kind.dynamicType)")
handleObject(kind as dynamicType)
}
I suspect that handling this use case might pose the most difficulties when
implementing the feature. It might make the whole thing impossible if
there's no way to resolve types at run-time in compiled code. For example,
if the dispatcher is in a Framework distributed as a binary and the user
does
class MyClass {}
func handleObject(obj: MyClass) { print "Success!" }
let stuff = MyClass()
dispatchToHandler(stuff)
in the project's code, what would happen?
Casting to an intermediate type between the static and dynamic types would
fall out naturally, though in that case you'd already have to know the
dynamicType and write the explicit intermediate type name in the code. If
that much is known then it's possible to cast directly to that intermediate
type with existing syntax.
Also, it's worth noting that the "Any" case is only the broadest instance
possible. Anything that passes data along as a super type, by using a
Protocol as a concrete type specifier, etc. could benefit from this
mechanism.
Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160108/00aa6b16/attachment.html>
More information about the swift-evolution
mailing list