I'm trying to add a mutating method through Array extension. I'm creating a 2D array to do some calculations. But strangely Xcode is throwing me below error while creating 2D array
error: cannot convert value of type '[Int]' to expected argument type 'Int'. var bucket : [[Int]] = Array.init(repeating: Int, count: base)
My playgound code is this ,
extension Array where Element == Int {
public mutating func someTestMethod() {
let base = 10
var bucket : [[Int]] = Array.init(repeating: [Int](), count: base)
// Some Other Code
}
}
Where as the below code is working fine,
extension Array where Element == Int {
public mutating func someTestMethod() {
let base = 10
var bucket : [[Int]] = .init(repeating: [Int](), count: base)
// Some Other Code
}
}
Would like know why is this happening since type inference should work in both cases. I would appreciate any help in understanding what is happening here.
CodePudding user response:
When omit the type for the init by only writing .init
var bucket : [[Int]] = .init(repeating: [Int](), count: base)
then the compiler deduces the init to call from the contextual type you have given, var bucket : [[Int]]
so the complete init call is
Array<[Int]>.init(repeating: [Int](), count: base)
but if you use Array.init
then the compiler uses the actual type of the extension which is given from the where
condition to be Array<Int>