قالب وردپرس درنا توس
Home / IOS Development / Swift Tips: Vector Calculus with protocols

Swift Tips: Vector Calculus with protocols



Last week's Swift Talk we discussed the vector calculator required to build a flow chart for our running program. To find out where the tracks overlap, we needed to calculate the nearest distance from one point to a line segment.

We do not want to repeat the math here, but we want to highlight a detail of the implementation.

For testing purposes we wanted to calculate with CGPoint s, which makes it easy to draw the points in a view. In the final app, we will calculate with Core Location coordinates. It is important to note that geographic coordinates are coordinates in a sphere, but for our use, we suggested that the earth is flat – it is a good enough approach for the small region we are dealing with.

Instead of implementing the vector operation first on CGPoint and then writing them on CLLocationCoordinate2D we decided to introduce a single protocol:

  Protocol Vector2 {
Associated Type Component: Numeric
was x: component {get}
were y: Component {get}
init (x: component, y: component)
}

This protocol represents a vector with two numeric components, x and y . We use an associated type to specify the type of components: in our case, they may be of the type CGFLoat (for CGPoint ) or CLLocationDegrees CLLocationCoordinate2D ) . Since CGPoint already has all protocol requirements, it corresponds to Vector2 is a one-liner:

  extension CGPoint: Vector2 {}

Now we can begin defining vector operations on the Vector2 protocol, such as the point product and the vector add-on:

  Extension Vector2 {
func dot (_ others: self) -> component {
return x * other.x + y * other.y
}

static func + (l: self, r: self) -> even {
return yourself (x: l.x + r.x, y: l.y + r.y)
}
}

Since the operation is defined on the protocol, we will get all of them free when we adhere to a new type of protocol; for example with CLLocationCoordinate2D :

  extension CLLocationCoordinate2D: Vector2 {
was x: CLLocationDegrees {return length}
where y: CLLocationDegrees {return latitude}
init (x: CLLocationDegrees, y: CLLocationDegrees) {
self.init (latitude: y, longitude: x)
}
}

To learn more, the first episode of this collection is public. To follow our progress, you can subscribe. 🤓


Source link