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

时间:2017-08-17 07:15:48

标签: arrays swift hashtable

我正在使用链表实现哈希表。 共有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)

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra java.time.format.Parsed.getLong(Parsed.java:203) java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298) java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2540) java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179) java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1746) java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720) 参数是数组元素类型的实例, e.g。

repeating:

创建一个buckets = Array<Bucket>(repeating: Bucket(), count: capacity) 的数组。这可以简化为

Bucket

由于自动类型推断。

然而,(正如您在此期间注意到的那样)buckets = Array(repeating: Bucket(), count: capacity) 是一个类,这将创建一个包含对相同对象实例的多个引用的数组,这不是你想要的。可能的解决方案是

Bucket

了解更多信息,请参阅Swift: Creating an Array with a Default Value of distinct object instances