[swift-users] Still can't derive from a generic class

Joanna Carter joanna at carterconsulting.org.uk
Fri Sep 1 03:37:15 CDT 2017


Hi Joe

Thanks for your input on this.

> This is likely due to the runtime not handling cycles properly in type metadata initialization—a subclass T needs its base class metadata for BaseObject<T>, which in turn needs the metadata for T to instantiate the generic type. This is something we plan to fix next year since it requires runtime ABI changes.

Hmmm. I'm finding this really frustrating, waiting for features that I have been using for years, in another popular language (C#), to see the light of day.

Maybe application programmers are happy with Swift so far but, when it comes to my speciality of designing frameworks, I am constantly finding myself blocked by lack of metadata APIs :-(

I am talking about a couple of frameworks that underpin one of the largest business management systems in Europe, for which the client is asking a MacOS/iOS version.

> Would a protocol-based approach suffice? `Self` in a protocol extension would give you access to the concrete type in a similar way:
> 
> protocol Base: AnyObject {
>  var properties:  [PartialKeyPath<Self> : AnyProperty] { get }
> }
> 
> extension Base {
>  func value<T>(for keyPath: KeyPath<Self, T>) -> T?
>  {
>    guard let property = properties[keyPath] else
>    {
>      return nil
>    }
> 
>    return property.getValue()
>  }
> 
>  /*etc.*/
> }
> 
> class Test: Base {
>  let properties = [\Test.name: Property<String>()]
> 
>  var name: String {
>    get { return value(for: \.name) }
>    set { set(value: newValue, for: \.name) }
>  }
> }

At first glance, I thought, Yes! But then I realised that this then requires a final class to cater for the use of Self in the protocol; something that would be a blocker for the class hierarchies that most users of the framework would want to create on top of the Base functionality.

I suppose I could look at using protocol-oriented composition but trying to avoid associated types in protocols in frameworks that use generics extensively is akin to hitting yourself repeatedly on the head with a hammer ;-)

And I really don't want to have to keep on repeating type-erasure boilerplate code to achieve that.

I think the realisation that I may well lose the chance of a pretty massive contract and that my client will lose an important business opportunity is finally dawning :-(

Joanna

--
Joanna Carter
Carter Consulting



More information about the swift-users mailing list