user7418039 user7418039 - 10 months ago 69
Swift Question

Type error while initializing fixed size array in Swift

I'm in the middle of implementing Hash Table using a linked list.
There are total 3 classes.

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
}


When I initialize the HashTable instance, I want to make a fixed size array which is a type of Bucket(or HashTableBucket) with nil values. I essentially want to make
[[], [], [], [], []]
I'm getting an error on the line
buckets = Array<Bucket>(repeating: [], count: capacity)
. The error says,

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)


What am I doing wrong here?

Answer Source

The repeating: argument is an instance of the array's element type, e.g.

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

to create an array of Buckets. This can be simplified to

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

due to automatic type inference.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download