ThatMan
ThatMan

Reputation: 165

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

Upvotes: 4

Views: 2089

Answers (1)

Luca Angeletti
Luca Angeletti

Reputation: 59496

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
    }
}

Upvotes: 2

Related Questions