Swift 4中泛型类型的扩展

时间:2017-06-17 23:21:49

标签: swift swift4

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

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 }
    }
}

只有当DataSetElement时才会有大量适用于TwoDimensionalDataPoint的方法。所以我做了一个像这样的扩展:

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
        }
    }
}

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

  

'DataSet.Element'类型的值(又名   'OneDimensionalDataPoint')没有成员'x'

这不应该没问题,因为我在扩展名中将Element约束为TwoDimensionalDataPoint吗?

1 个答案:

答案 0 :(得分:1)

在我将其弹出Xcode之后,我能够更好地了解正在发生的事情,

您的问题是您的类型别名会覆盖您的通用类型

将您的通用名称重命名为def my_project(): #Your other code here my_project() while True: finish_input = input("Would you like to search again: (Y/N) > ") if finish_input.lower() == "y": my_project() elif finish_input.lower() == "n": print("\nThank you for using this service.") break else: print("\nInvalid entry. Please enter Y or N") ,并将元素指定给T

T

或您的类型:

public typealias Element = T

或者只是将所有类型都放在一起。