Search code examples
for-loopswiftcastingsprite-kitsknode

Swift: typecasting in a for loop


I'm a noobie in Swift. I'm trying to iterate over SKNodeTree and check if there are scary monster Nodes here. However I cannot figure out how to typecase the for loop. I have understood that this would be possible with "as" clause.

By the way, is comparing strings with == ok in Swift?

      for monsterNode in self.children{
          if (monsterNode.name? == "scary") {
                println("scary monster here")
          }
      }

Solution

  • Comparing strings can be done by using == instead of isEqualToString, so thats fine. Your code should be like this:

    for monsterNode in self.children as [SKNode] {
        if (monsterNode.name? == "scary") {
              println("scary monster here")
        }
    }
    

    You can submit your cast inside the brackets []