Swift 4 中通用类型的扩展

Extensions of generic types in Swift 4

我有两个协议和一个通用结构:

public protocol OneDimensionalDataPoint {
    /// the y value
    var y: Double { get }        
}

public protocol TwoDimensionalDataPoint: OneDimensionalDataPoint {
    /// the x value
    var x: Double { get }
}

public struct DataSet<Element: OneDimensionalDataPoint> {
    /// the entries that this dataset represents
    private var _values: [Element]
    //...implementation
}

extension DataSet: MutableCollection {
    public typealias Element = OneDimensionalDataPoint
    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 {
        get{ return _values[position] }
        set{ self._values[position] = newValue }
    }
}

只有当 ElementTwoDimensionalDataPoint 时,才有大量方法适用于 DataSet。所以我做了这样的扩展:

extension DataSet where Element: TwoDimensionalDataPoint {
    public mutating func calcMinMaxX(entry e: Element) {
        if e.x < _xMin {
            _xMin = e.x
        }
        if e.x > _xMax {
            _xMax = e.x
        }
    }
}

编译器不喜欢这样,并说:

Value of type 'DataSet.Element' (aka 'OneDimensionalDataPoint') has no member 'x'

这不是很好吗,因为我在扩展中将 Element 限制为 TwoDimensionalDataPoint

将其放入 Xcode 后,我能够更好地理解发生了什么,

你的问题是你的类型别名覆盖了你的通用类型,

将您的通用名称重命名为 T 并将元素分配给 T

public typealias Element = T

或您的类型别名:

public typealias DataElement = OneDimensionalDataPoint

或者将类型别名一起删除。