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

Joanna Carter joanna at carterconsulting.org.uk
Wed Mar 23 13:29:50 CDT 2016


Hi Joe

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

Hmm… I've been playing with this for days now and, as useful as your code is for instantiating a given type, what I need to do is instantiate a generic type, bound to that given type.

Something along the lines of…

public protocol PropertyProtocol
{
  var untypedValue: Any? { get }
}

public struct Property<PropertyType : Any>
{
  public let info: PropertyInfo
  
  public var name: String
  {
    return info.name
  }
  
  public var displayName: String
  {
    return info.displayName
  }
  
  public var value: PropertyType?
  
  public init()
  {
    self.init(propertyInfo: PropertyInfo(), value: nil)
  }
  
  init(propertyInfo: PropertyInfo, value: PropertyType?)
  {
    self.value = value
    
    self.info = propertyInfo;
  }
  
  init(propertyInfo: PropertyInfo)
  {
    self.init(propertyInfo: propertyInfo, value: nil)
  }
  
  init(other: Property<PropertyType>)
  {
    self.init(propertyInfo: other.info, value: other.value)
  }
}

struct PropertyFactory
{
  static func createBoundPropertywithValueType(valueType: Any.Type) -> PropertyProtocol
  {
    return Property<valueType>.init()
  }
}

Of course, Ive still got a lot of C# cruft in my thinking so I am more than willing to admit I may not be approaching this in the right way ;-)

Joanna

--
Joanna Carter
Carter Consulting



More information about the swift-evolution mailing list