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

Joanna Carter joanna at carterconsulting.org.uk
Wed Aug 30 13:16:58 CDT 2017


Hi Kenny

> Just curious, and because I have a distinct lack of imagination: can you share a concrete case of this pattern?

class BaseObject<rootType>
{
  private let properties: [PartialKeyPath<rootType> : AnyProperty]
  
  init(properties: [PartialKeyPath<rootType> : AnyProperty])
  {
    self.properties = properties
  }
  
  func value<valueType>(for keyPath: KeyPath<rootType, valueType>) -> valueType?
  {
    guard let property = properties[keyPath] else
    {
      return nil
    }
    
    return property.getValue()
  }
  
  func set<valueType>(value: valueType?, for keyPath: KeyPath<rootType, valueType>)
  {
    guard let property = properties[keyPath] else
    {
      return
    }
    
    property.set(value: value)
  }
}

class Test : BaseObject<Test>
{
  var name: String?
  {
    get
    {
      return value(for: \.name)!
    }
    set
    {
      set(value: newValue, for: \.name)
    }
  }
  
  var number: Int?
  {
    get
    {
      return value(for: \.number)!
    }
    set
    {
      set(value: newValue, for: \.number)
    }
  }
  
  init()
  {
    super.init(properties: [\Test.name : Property<String>(), \Test.number : Property<Int>()])
  }
}

Without the generic rootType parameter, all the getter and setter methods need an explicit mention of the derived class for the keypath :

class Test : BaseObject
{
  var name: String?
  {
    get
    {
      return value(for: \Test.name)!
    }
    set
    {
      set(value: newValue, for: \Test.name)
    }
  }
  
  …
}

It was all so simple in C# :(

Joanna

--
Joanna Carter
Carter Consulting



More information about the swift-users mailing list