在 Swift 中初始化固定大小数组时出现类型错误

Type error while initializing fixed size array in Swift

我正在使用链表实现 Hash Table。 共有 3 个 类.

    class HashNode<Key: Hashable, Value> {
        var key: Key
        var value: Value
        var next: HashNode?

        init(key: Key, value: Value) {
            self.key = key
            self.value = value
        }
    }

    class HashTableBucket<Key: Hashable, Value> {
        typealias Node = HashNode<Key, Value>
        var head: Node?
        var tail: Node?

        func addNode(newNode: Node) {
            //code
        }

        func findNode(key: Key) -> Node?{
             //code
        }
}

struct HashTable<Key: Hashable, Value> {
    private typealias Bucket = HashTableBucket<Key, Value>
    private var buckets: [Bucket]

    private(set) public var count = 0
    private(set) public var capacity = 0

    init(capacity: Int) {
        assert(capacity > 0)
        buckets = Array<Bucket>(repeating: [], count: capacity)
    }

    //other code
}

当我初始化 HashTable 实例时,我想创建一个固定大小的数组,它是一种具有 nil 值的 Bucket(或 HashTableBucket)类型。我基本上想 [[], [], [], [], []] 我在行 buckets = Array<Bucket>(repeating: [], count: capacity) 上收到错误。错误说,

Playground execution failed: error: HashTable.xcplaygroundpage:163:19: error: cannot invoke initializer for type 'Array<HashTableBucket<Key, Value>>' with an argument list of type '(repeating: [Any], count: Int)'
        buckets = Array<Bucket>(repeating: [], count: capacity)
                  ^

HashTable.xcplaygroundpage:163:19: note: expected an argument list of type '(repeating: Element, count: Int)'
        buckets = Array<Bucket>(repeating: [], count: capacity)

我做错了什么?

repeating:参数是数组元素类型的一个实例, 例如

buckets = Array<Bucket>(repeating: Bucket(), count: capacity)

创建一个 Bucket 数组。这可以简化为

buckets = Array(repeating: Bucket(), count: capacity)

由于自动类型推断。

但是,(正如您同时注意到的:) Bucket 是一个 class,这将创建一个数组,其中包含对 same 对象实例,这不是您想要的。一个可能的解决方案是

buckets = (0..<capacity).map { _ in Bucket() }

有关更多信息,请参阅