I made a simple sample code using protocol and generic.
I want to call doSomething() inside the foo() function.
The following calls work well, and the logs are printed as I expected.
simpleA.doSomething(item: 300) // print -> [SimpleA] value property: 100, item argument: 300
simpleB.doSomething(item: 400) // print -> [SimpleB] value property: 200.0, item argument: 400.0
The following syntax inside the foo() function results in a compilation error.
simple.doSomething(item: 500)
simple.doSomething(item: 600)
Can't I pass the Int or Double value as a parameter inside doSomething?
protocol SimpleProtocol {
associatedtype MyType
func doSomething(item: MyType)
}
struct SimpleA<T>: SimpleProtocol {
typealias MyType = T
private let value: T
init(value: T) {
self.value = value
}
func doSomething(item: T) {
print("[SimpleA] value property: \(value), item argument: \(item)")
}
}
struct SimpleB<T>: SimpleProtocol {
typealias MyType = T
private let value: T
init(value: T) {
self.value = value
}
func doSomething(item: T) {
print("[SimpleB] value property: \(value), item argument: \(item)")
}
}
class Sample {
func debugMethod() {
let simpleA = SimpleA<Int>(value: 100)
let simpleB = SimpleB<Double>(value: 200)
// It works well
simpleA.doSomething(item: 300) // print -> [SimpleA] value property: 100, item argument: 300
simpleB.doSomething(item: 400) // print -> [SimpleB] value property: 200.0, item argument: 400.0
// It doesn't work well.
foo(simpleA)
foo(simpleB)
}
func foo<P: SimpleProtocol>(_ simple: P) {
// Compile Error
// error: cannot convert value of type 'Int' to expected argument type 'P.MyType'
simple.doSomething(item: 500)
simple.doSomething(item: 600)
simple.doSomething(item: 700)
}
}