在 Swift 中初始化固定大小数组时键入错误



我正在使用链表实现哈希表。 共有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是一个类,这将创建一个数组,其中包含对同一对象实例的多个引用,这不是您想要的。一个可能的解决方案是

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

有关更多信息,请参阅 Swift:创建具有不同对象实例默认值的数组。

最新更新