[swift-evolution] Binding generic types using a metatype parameter

Joe Groff jgroff at apple.com
Wed Mar 23 13:08:19 CDT 2016


> On Mar 23, 2016, at 10:13 AM, Joanna Carter via swift-evolution <swift-evolution at swift.org> wrote:
> 
> I'm not sure if this is an appropriate conversation to bring this up on but, here goes.
> 
> I have a need, for serialisation and various other uses, to be able to create an instance of a generic type, with the parameter type(s) stored in (a) var(s) of Any.Type.
> 
> Typically, the origin of the metatype is something like a Mirror's subjectType property.
> 
> Some of the proposals for Swift 3 seem to touch on similar needs but I was not sure whether to pollute those discussions or not

You can accomplish this with Swift today by casting your Any.Type to a Protocol.Type that provides an initializer:

protocol Deserializable {
  init(deserializedFrom stream: DeserializationStream)
}

func deserializeValue(type type: Any.Type, from stream: DeserializationStream) -> Any? {
  if let deserializableType = type as? Deserializable.Type {
    return deserializableType.init(deserializedFrom: stream)
  }
  return nil
}

-Joe


More information about the swift-evolution mailing list