Edit: I have restated and hopefully clarified this question over here. Now I\'ve added the solution.
I\'ve defined a function (see foo()
in attached example
I know what the problem is. Not sure if my solution is the best answer.
The problem is that both your associatedtypes have associatedtypes themselves.
So in the extension, the Swift compiler can't figure out the type of the associatedtypes — unless you constrain it.
Like do:
extension LineProtocol where Self.VectorType == Vector, Self.PointType == Point {
public func foo() -> Self.PointType {
return (anchor + direction)
}
}
Your code works for your concrete type Line
, because both your associatedtypes have their requirements fulfilled ie:
public typealias PointType = Point // makes compiler happy!
public typealias VectorType = Vector // makes compiler happy!
FWIW you could have got rid of the explicit conformance to your associatedtype requirements and let the compiler infer1 conformance to your associatedtypes requirements and write your Line
type as such:
public struct Line: LineProtocol {
public var anchor: Point
public var direction: Vector
public init(anchor: Point, direction: Vector) {
self.anchor = anchor
self.direction = direction
}
public func bar() -> Point {
return (anchor + direction)
}
}
1: Generics - Associated Types
Thanks to Swift’s type inference, you don’t actually need to declare a concrete Item of Int as part of the definition of IntStack. Because IntStack conforms to all of the requirements of the Container protocol, Swift can infer the appropriate Item to use, simply by looking at the type of the append(_:) method’s item parameter and the return type of the subscript. Indeed, if you delete the typealias Item = Int line from the code above, everything still works, because it’s clear what type should be used for Item.