Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert value of type 'String' to expected argument type 'SKNode'

There is an issue on last line. How can I fix that? Issue says ''Cannot convert value of type 'String' to expected argument type 'SKNode'. '' Here is my code :

import SpriteKit

let BallCategoryName = "ball"

class GameScene: SKScene {

    let ball = childNodeWithName(BallCategoryName) as! SKSpriteNode
like image 255
ThatMan Avatar asked Sep 18 '25 08:09

ThatMan


1 Answers

The problem

You are using self before the object initialisation.

Infact writing this

let ball = childNodeWithName(BallCategoryName) as! SKSpriteNode

is equals to writing this

let ball = self.childNodeWithName(BallCategoryName) as! SKSpriteNode

But during the properties initialisation the current instance of GameScene does not exists yet! So there's no self yet.

And this is a good thing because if the compiled had allowed this code, it would have crashed at runtime since there is no ball node in you Scene yet (again because there is no Scene yet).

Solution

I suggest you to

  1. turn your stored property into a computed property
  2. use a lowercase character for the first name of a property like this ballCategoryName
  3. prefer conditional casting (as? instead of as!)
  4. turn the global constant ballCategoryName into a stored property

The code

class GameScene: SKScene {
    let ballCategoryName: String = "ball"
    var ball: SKSpriteNode? {
        return childNodeWithName(ballCategoryName) as? SKSpriteNode
    }
}
like image 53
Luca Angeletti Avatar answered Sep 19 '25 22:09

Luca Angeletti