I have a problem with a generic delegate ProducerDelegatethat will have an argument ( Int) with the same type that the method IntConsumer( Int) needs it
If delegate methods are called and I want to use the resulting value element
func didProduce<Int>(from: Producer<Int>, element: Int) {
output(element: element)
}
to call another method, I got an error:
Cannot convert value of type 'Int' to expected argument type 'Int'
And my question is: why?
I will explain my case (and here is the playground file with the same source: http://tuvalu.s3.amazonaws.com/so/generic-delegate.playground.zip )
I have a generic manufacturers class Producerwith a protocol for the created elements ProducerDelegate:
import Foundation
protocol ProducerDelegate : class {
func didProduce<T>(from: Producer<T>, element: T)
}
class Producer<T> {
weak var delegate: ProducerDelegate?
let element: T
init(element: T) {
self.element = element
}
func produce() {
delegate?.didProduce(from: self, element: element)
}
}
In the consumer, the manufacturer introduces:
/// Consumes produced `Int` elements and work with it
class IntConsumer {
/// Producer of the `Int`s
let producer: Producer<Int>
/// Initializes and returns a `IntConsumer` having the given producer
///
/// - Parameters:
/// - producer: `Int` producer
init(producer: Producer<Int>) {
self.producer = producer
self.producer.delegate = self
}
/// outputs the produced element
fileprivate func output(element: Int) {
print(element)
}
}
Now I need to add the extension for the delegate as follows:
extension IntConsumer: ProducerDelegate {
func didProduce<Int>(from: Producer<Int>, element: Int) {
output(element: element)
}
}
But this fails:
Cannot convert value of type 'Int' to expected argument type 'Int'
Swift , Int, :
func didProduce<Int>(from: Producer<Int>, element: Int) {
output(element: element as! Int)
}
, String, :
func didProduce<String>(from: Producer<String>, element: String) {
guard let element2 = element as? Int else { return }
output(element: element2)
}
, - typealias, :
extension IntConsumer: ProducerDelegate {
typealias T = Int
func didProduce<T>(from: Producer<T>, element: T) {
guard let element = element as? Int else { return }
output(element: element)
}
}
, - .