I'd like to increase my knowledge of generics and I come to a problem I can't solve. I have two different types (Int
and Double
). Both types implement a function advanced(by:)
. I want to make a generic function to call advanced(by:)
on a given type.
The benefit would be so that I could replace intAdvancedByTen(value:)
and doubleAdvancedByTen(value:)
with a single genericAdvancedByTen(value:)
.
Here's my playground:
let myDouble: Double = 1
let myInt: Int = 2
func intAdvanceByTen(value: Int) { // Replace this function
value.advanced(by: 10)
}
func doubleAdvanceByTen(value: Int) { // ...and this function
value.advanced(by: 10)
}
protocol CanAdvance {
func advance(_ by: Any)
}
// ...with this generic function
func genericAdvanceByTen(value: CanAdvance) {
value.advance(10)
}
genericAdvanceByTen(value: myInt) // Error: Argument "Int" does not conform to expected type "CanAdvance"
How to make the generic function know that the passed type implements the advanced(by:)
method?