4

I'm trying to learn about how to do something simple with the generics facility in Swift. I've boiled one problem that I was facing down to a simple puzzle. Imagine that I want to write a value type Pair<A,B> that has a flip method on it that returns a copy of the pair, but with the two values (and their types) reversed.

struct Pair<A, B> {
    let a: A
    let b: B

    init(first: A, second:B) {
        a = first;
        b = second;
    }

    func flip() -> Pair<B,A> {
        return Pair(self.b,self.a)
    }
}

When I write this I get an error on the line where I'm trying to return the new flipped pair. Cannot convert the expression's type 'Pair<A,B>' to type (first: A, second: B)'

Is what I'm trying to do even possible?

pohl
  • 3,158
  • 1
  • 30
  • 48

1 Answers1

6

Certainly this is possible, since Pair<B,A> is a perfectly valid type in the context of the generic definition.

There are two problems with your code, namely:

  1. Argument labels are required for your init method: ...(first: self.b, second: self.a).

  2. After fixing the above, the error becomes "'B' is not convertible to 'A'". The compiler apparently does not infer that Pair in the definition of flip() refers to Pair<B,A> (the function's return type) rather than Pair<A,B>. So you must explicitly call Pair<B,A>(first: self.b, second: self.a).

You may or may not consider the latter to be a bug; if so, file a report!

jtbandes
  • 115,675
  • 35
  • 233
  • 266