swift 中的类型推断
Type Inference In swift
我正在尝试通过数组扩展添加一个变异方法。我正在创建一个二维数组来进行一些计算。但奇怪的是 Xcode 在创建 2D 数组时让我出错
error: cannot convert value of type '[Int]' to expected argument type 'Int'. var bucket : [[Int]] = Array.init(repeating: Int, count: base)
我的游戏机代码是这样的,
extension Array where Element == Int {
public mutating func someTestMethod() {
let base = 10
var bucket : [[Int]] = Array.init(repeating: [Int](), count: base)
// Some Other Code
}
}
下面的代码运行良好,
extension Array where Element == Int {
public mutating func someTestMethod() {
let base = 10
var bucket : [[Int]] = .init(repeating: [Int](), count: base)
// Some Other Code
}
}
想知道为什么会发生这种情况,因为类型推断在这两种情况下都应该有效。如果能帮助我理解这里发生的事情,我将不胜感激。
当只写 .init
省略 init 的类型时
var bucket : [[Int]] = .init(repeating: [Int](), count: base)
然后编译器从您提供的上下文类型中推断出要调用的 init,var bucket : [[Int]]
所以完整的 init 调用是
Array<[Int]>.init(repeating: [Int](), count: base)
但是如果您使用 Array.init
,那么编译器会使用根据 where
条件给出的实际扩展类型 Array<Int>
我正在尝试通过数组扩展添加一个变异方法。我正在创建一个二维数组来进行一些计算。但奇怪的是 Xcode 在创建 2D 数组时让我出错
error: cannot convert value of type '[Int]' to expected argument type 'Int'. var bucket : [[Int]] = Array.init(repeating: Int, count: base)
我的游戏机代码是这样的,
extension Array where Element == Int {
public mutating func someTestMethod() {
let base = 10
var bucket : [[Int]] = Array.init(repeating: [Int](), count: base)
// Some Other Code
}
}
下面的代码运行良好,
extension Array where Element == Int {
public mutating func someTestMethod() {
let base = 10
var bucket : [[Int]] = .init(repeating: [Int](), count: base)
// Some Other Code
}
}
想知道为什么会发生这种情况,因为类型推断在这两种情况下都应该有效。如果能帮助我理解这里发生的事情,我将不胜感激。
当只写 .init
var bucket : [[Int]] = .init(repeating: [Int](), count: base)
然后编译器从您提供的上下文类型中推断出要调用的 init,var bucket : [[Int]]
所以完整的 init 调用是
Array<[Int]>.init(repeating: [Int](), count: base)
但是如果您使用 Array.init
,那么编译器会使用根据 where
条件给出的实际扩展类型 Array<Int>