2017-06-16 56 views
1

我試圖在斯威夫特4.自定義集合類,我實現: startIndexendIndexindex(after:)subscript(Element)subscript(Range<Element>),並已指定類型Element。爲什麼我得到這個錯誤?「收藏」需要的各類「MyCollectionClass.Element」和「片<MyCollectionClass>」相當於

extension MyCollectionClass: Collection { 
    public typealias Element = MyCollectionElement 

    public var startIndex: Int { 
     return _values.startIndex 
    } 

    public var endIndex: Int { 
     return _values.endIndex 
    } 

    public func index(after: Index) -> Index { 
     return _values.index(after: after) 
    } 

    public subscript(position: Index) -> Element { 
     return _values[position] 
    } 

    public subscript(bounds: Range<Index>) -> SubSequence { 
     return _values[bounds] 
    } 
} 

「收藏」要求類型「MyCollectionClass.Element」和「切片< MyCollectionClass>」相當於

回答

2

這是一個完全無用的錯誤信息(我會在鼓勵你file a bug ) - 問題是雙重的:

  • 你混淆了編譯器的交替使用IntIndex
  • 您指的是SubSequence而實際上並未滿足關聯類型。

您可以只定義類型別名,以明確地同時滿足IndexSubSequence相關類型的解決這兩個:

public class MyCollectionClass<MyCollectionElement> { 
    var _values = [MyCollectionElement]() 
} 

extension MyCollectionClass: Collection { 

    public typealias Element = MyCollectionElement 
    public typealias Index = Int 

    // as ArraySlice is Array's SubSequence type. 
    public typealias SubSequence = ArraySlice<MyCollectionElement> 

    public var startIndex: Index { 
     return _values.startIndex 
    } 

    public var endIndex: Index { 
     return _values.endIndex 
    } 

    public func index(after: Index) -> Index { 
     return _values.index(after: after) 
    } 

    public subscript(position: Index) -> Element { 
     return _values[position] 
    } 

    public subscript(bounds: Range<Index>) -> SubSequence { 
     return _values[bounds] 
    } 
} 

雖然注意,您不必執行subscript(bounds:)要求 - Collection爲此提供了一個默認實現,它僅返回Slice<Self>

另外,如果可能的話,我想你(假定)的通用佔位符重命名只是爲了Element,並讓編譯器推斷佔位滿足從標聲明Element相關類型:

public class MyCollectionClass<Element> { 
    var _values = [Element]() 
} 

extension MyCollectionClass: Collection { 

    public typealias Index = Int 

    public var startIndex: Index { 
     return _values.startIndex 
    } 

    public var endIndex: Index { 
     return _values.endIndex 
    } 

    public func index(after: Index) -> Index { 
     return _values.index(after: after) 
    } 

    public subscript(position: Index) -> Element { 
     return _values[position] 
    } 
}