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

Joanna Carter joanna at carterconsulting.org.uk
Thu Mar 24 07:16:18 CDT 2016


Well, I've been playing some more and come up with an idea that seems to be thwarted by the compiler…

protocol PropertyFactory
{
  
}

extension PropertyFactory
{
  // what I'd like to do but that doesn't compile
  static func createProperty() -> PropertyProtocol
  {
    return Property<Self.Type>()
  }
  
// what it seems I have to do to satisfy the compiler
  static func createProperty(valueType: Any.Type) -> PropertyProtocol
  {
    switch self // this is a really naff and limited workaround
    {
      case is Int.Type:
        return Property<Int>()
      // ...
      default: fatalError("Unexpected type \(self)")
    }
  }
}

extension Int : PropertyFactory
{
  
}

// calling code works fine

    let type: PropertyFactory.Type = Int.self
    
    var property = type.createProperty(type) as? Property<Int>
      
    property?.value = 123
      
    print(property?.untypedValue)
    
… but it does mean that all possible types would have to be extended to implement PropertyFactory.

Does this make a case for either :

Extend the generic syntax to allow for something like

struct GenericStruct<ValueType : Any.Type>
{
  func doSomething<ParamType : MyType.Type>()
  {
    …
  }
}

… or having something like the following that knows how to bind a generic type to its parameter types …

protocol AnyGeneric // all generic types implement this protocol
{

}

extension AnyGeneric
{
  static func bindToParameterType(parameterType: Any.Type) -> Any.Type
  {
    // return something akin to Self<parameterType>
  }
}

The more I think about it, the latter option seems slightly screwy but I include it as a discussion point.

Joanna

--
Joanna Carter
Carter Consulting



More information about the swift-evolution mailing list