Two-tuple array initialization fails
I have a simple function that returns an array of tuples
func findNodeNeighbors(node: Node) -> [(node: Node, distance: Double)] {
var neighbors = [(node: Node, distance: Double)]()
var nodeLinks = linksWith(node)
for link in nodeLinks {
neighbors.append((node: link.otherNodeLinkedWith(node), distance: link.length))
}
return neighbors
}
But this turns out to be an error Invalid use of () to call a clue of non-function type
in the first line of the function body.
If, instead, I declare the type for neighbors
explicitly, everything is fine.
var neighbors: [(node: Node, distance: Double)] = []
How did it happen?
I've read that it's preferable to declare arrays by initializing them and allowing implicit type inference.
source to share
This is pretty sure a bug in Swift parse, especially for sugar [Type]
when combined with named tuples.
var neighbors = Array<(node: Node, distance: Double)>()
(which should be identical [(node: Node, distance: Double)]()
) works fine.
edit: it looks like the dictionary equivalent has the same problem
Works great:
var d = Dictionary<Int,(x: Int, y: Int)>()
Bust:
var d = [Int:(x: Int, y: Int)]()
source to share
what if I want an empty array to be the initial one?
I'm not 100% sure, but I think another way you can quickly get around this problem currently is to declare the tuple with typealias
.
For example:
typealias Test = (Node, Double)
func findNodeNeighbors(node: Node) -> [Test] {
var neighbors = [Test]()
//etc
}
source to share