Say you have a protocol ToString
that is implemented for Int
, and a function that takes an array of ToString
s.
Trying to pass an array of Int
s to this function results in the error Cannot convert value of type '[Int]' to expected argument type '[ToString]'
.
However, using map
on the array before passing it to the function works. Is this the supposed way to do the type cast or is there a way that doesn't result in iterating over the array? Or is this optimized out by the compiler?
Full example:
protocol ToString {
func toString() -> String
}
extension Int: ToString {
func toString() -> String {
return "\(self)"
}
}
func log( values: [ToString]) {
values.forEach { print( $0.toString()) }
}
let values: [Int] = [1, 2, 3]
// Error: Cannot convert value of type '[Int]' to expected argument type '[ToString]'
log( values)
// No error
log( values.map { $0 })