Pedro Paulo Amorim
Pedro Paulo Amorim

Reputation: 1949

How to correctly use generics with protocols and different types?

I have the script below written in Swift 5 and I am doing something wrong to configure the generics.

Basically it's a Foo protocol with a function with has an argument with a generic type and it's implemented in both Fez and Foz, where the type of the bar function is defined in the class definition. By using associatedtype is possible to fix this?

Any idea of what could be and how to solve it? Am I doing something wrong with the setup of generics? I need to support both Int and String.

protocol Foo {
  func bar<T>(zed: T)
}

class Fez: Foo {
  private var zed: Int = 0
  func bar<Int>(zed: Int) {
    self.zed = zed            //Cannot assign value of type 'Int' to type 'Swift.Int'
  }
}

class Foz: Foo {
  private var zed: String = ""
  func bar<String>(zed: String) {
    self.zed = zed            //Cannot assign value of type 'String' to type 'Swift.String'
  }
}

Thank you very much.

For the downvoter: I hope you have a nice day.

Upvotes: 0

Views: 92

Answers (1)

Rob Napier
Rob Napier

Reputation: 299275

A generic like this says that the caller can choose any type to pass to bar, and the implementation will handle it. You mean that the implementation gets to decide what type it can be passed, and that's an associatedtype as you suggest.

protocol Foo {
    associatedtype Zed
    func bar(zed: Zed)
}

class Fez: Foo {
  private var zed: Int = 0
  func bar(zed: Int) {
    self.zed = zed
  }
}

class Foz: Foo {
  private var zed: String = ""
  func bar(zed: String) {
    self.zed = zed
  }
}

Upvotes: 3

Related Questions