简体   繁体   中英

swift more efficient way to search array for match of different types

I am using Swift 3 to find a GKGraphNode in an array that has ax,y position that matches the target x,y position. Below is the init for the nodes. You can see each node has a vector_int2 coordinate called gridPosition. I create an array of these nodes to match my map's hexagonal grid.

class HexGraphNode : GKGraphNode {
var gridPosition: vector_int2!

required init(gridPosition: vector_int2) {
    super.init()

    self.gridPosition = gridPosition

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

}

I need to be able to search this array to find the node that occupies some specific grid coordinate. I am using the function below. This function works fine when the map is small like under 500 nodes. However, as the array grows, the program slows down to the point of being unacceptable. I need a more efficient way to search the array and find the matching node without starting from index zero each time. I have looked for other postings, but they always seem to compare objects of the same type. In this case I need to compare a property of the object (node.position) to a different type (vector_int2 which contains an x,y integer).

func node(atGridPosition position: vector_int2) -> NodeType {

    var result: NodeType!

    for node in self.nodes as! [NodeType] {

        if node.gridPosition.x == position.x && node.gridPosition.y == position.y {
            result = node

            break
        }
    }

    return result
}

Any help would be greatly appreciated.

If the grid positions of your nodes don't change dynamically, you could keep a dictionary of nodes rather than (or in addition to) you array. If you have a fixed (or maximum) width or height for your grid, the x,y coordinates can be converted to a single integer value to use as a key in the dictionary. Otherwise you could use a two level dictionary.

Accessing the nodes then would be an O(1) operation rather than O(n/2).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM