swiftsprite-kitnsstring

How can I identify all nodes whose name begins with "square" and ends with a number like "square1", "square2", etc inside of a child nodes with name?


I want to find all of the child nodes whose names begin with a certain text. I wanted to do it without writing hasPrefix, I thought there was a shorthand way for this. Something along the lines of

let someSquare = SKShapeNode()
someSquare.name = "square1"

let someOtherSquare = SKShapeNode()
someOtherSquare.name = "square2"

self.enumerateChildNodes(withName: "@%square") { stop, in
    
}

So the actual question I guess should be about that shorthand Objective-C NSString syntax or whatever for strings. I'm not sure what to call it. "@%square" or "%@square"? I remember seeing this somewhere, is this correct syntax?


Solution

  • The SpriteKit documentation includes the page Searching the Node Tree. It shows a syntax for advanced searches.

    If I'm reading that documentation correctly, you simply need:

    self.enumerateChildNodes(withName: "square[1-9]") { stop, in
        
    }
    

    This will match nodes with names "square1", "square2", ..., "square9".