[swift-users] Can't implement generic subscript in protocol

Joanna Carter joanna at carterconsulting.org.uk
Fri Sep 15 05:13:09 CDT 2017


Xcode Version 9.0 (9A235)

Hmmm. I'm now getting a segmentation fault : 11 on a constructor when trying to implement type erasure :

protocol DataProvider
{
  associatedtype ItemType
  
  subscript(index: Int) -> ItemType { get }
}

class _AnyDataProviderBoxBase<itemType>: DataProvider
{
  subscript(index: Int) -> itemType
  {
    fatalError()
  }
}

class _AnyDataProviderBox<providerType: DataProvider>: _AnyDataProviderBoxBase<providerType.ItemType>
{
  private let _subscript: (_ index: Int) -> providerType.ItemType
  
  init(_ base: providerType) // segmentation fault : 11
  {
    _subscript = base.subscript
  }
  
  override subscript(index: Int) -> providerType.ItemType
  {
    return _subscript(index)
  }
}

final class AnyDataProvider<providerType : DataProvider>: DataProvider
{
  private let box: _AnyDataProviderBox<providerType>
  
  init(_ base: providerType)
  {
    self.box = _AnyDataProviderBox(base)
  }
  
  subscript(index: Int) -> providerType.ItemType
  {
    return box[index]
  }
}

Joanna

--
Joanna Carter
Carter Consulting



More information about the swift-users mailing list