قالب وردپرس درنا توس
Home / IOS Development / Conform tuples to protocols

Conform tuples to protocols



Tuples in Swift is a great way to quickly combine two or more data. For example, when working with an SVG parsing library, we had two doubles that we wanted to combine. In some cases, it is very useful to create a nominal type, such as a Point :

  struct Point {
was x: Double
var y: Double
}

In other cases, we may not always come up with a good name. Maybe we are working on something more abstract, or the two values ​​can be interpreted in different ways: in one case they can be points, in another they are interpreted as sizes. Instead of a nominal type, we would use a structural type as a tuple:

  struct MyModel {
were couples: [(Double, Double)]
}

The main disadvantage of using a tuple to model data ̵

1; as we do above with (Double, Double) – is that a tuple cannot match a protocol. This means that we cannot just add Equatable Hashable or Codable conformance using the implementation we would otherwise get for free. If we had instead written the pairs as [Point] this would have been much easier.

However, everything is not lost. We can write a type Pair that works in the same way as a tuple, but also adds conditional matching. Here is a possible implementation:

  struct Pair  {
was one: A
were two: B
init (_ and: A, _ to: B) {
self.one = en
self.two = to
}
}

Now we can conditionally adapt Pairs to all kinds of protocols:

  extension Pairs: Encodable there A: Encodable, B: Encodable {}
extension Pair: Decodable where A: Decodable, B: Decodable {}
extension Pair: Equatable where A: Equatable, B: Equatable {}
extension Couple: Hashable where A: Hashable, B: Hashable {}

We can even customize Pair to SwiftUI's VectorArithmetic protocol so that it can be used with animatableData .

Of course, a Pair does not have the same syntactic sugar as a tuple, but it can be a quick alternative in case we want a structural type that can conform to Codable (or any other protocol): [19659002] struct MyModel {
were couples: [couple] }

Until Swift adds conditional conformity to the tuples, this is a solution that has served us well in a few projects.

Many of our projects include Swift Talk, our weekly couple programming video series. The latest collection explores SwiftUI as we build a client app for our Swift Talk backend.

To learn from us, you can subscribe here.


Source link