[swift-users] Can't implement generic subscript in protocol
Slava Pestov
spestov at apple.com
Fri Sep 15 18:28:48 CDT 2017
> On Sep 15, 2017, at 4:26 PM, Slava Pestov <spestov at apple.com> wrote:
>
>
>> On Sep 15, 2017, at 12:40 PM, Joanna Carter via swift-users <swift-users at swift.org> wrote:
>>
>> Xcode Version 9.0 (9A235)
>>
>> Hmmm. I'm now getting a segmentation fault : 11 on a constructor when trying to implement type erasure :
>
> Swift 4.0 had issues with members and member references named ‘subscript’. On master, I get the correct error message without crashing:
>
> Slavas-MBP:swift slava$ ../build/Ninja-ReleaseAssert/swift-macosx-x86_64/bin/swiftc sub.swift
> sub.swift:22:17: error: value of type 'providerType' has no member 'subscript'
> _subscript = base.subscript
> ^~~~ ~~~~~~~~~
>
> Indeed you’re not supposed to be able to refer to a subscript member like this. You could use a keypath, or try some other approach.
You could also write an explicit closure that loads the subscript:
let fn = { base[$0] }
Slava
>
> Slava
>
>>
>> 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
>>
>> _______________________________________________
>> swift-users mailing list
>> swift-users at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
>
More information about the swift-users
mailing list