Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It keeps telling me "Class 'GameScene' has no initializers"

Tags:

class

swift

import SpriteKit

class GameScene: SKScene {
    var movingGround: JTMovingGround!
    var hero: JTHero

    override func didMoveToView(view: SKView) {
       backgroundColor = UIColor(red: 159.0/255.0, green: 281.0/255.0, blue: 244.0/255.0, alpha: 1.0)
       movingGround = JTMovingGround(size: CGSizeMake(view.frame.width, 20))
        movingGround.position = CGPointMake(0, view.frame.size.height/2)
        addChild(movingGround)

        hero = JTHero()
        hero.position = CGPointMake(70, movingGround.position.y + movingGround.frame.size.height/2 + hero.frame.height/2)
        addChild(hero)
    }

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        movingGround.start()
    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}

could someone tell me what went wrong?? thanks

like image 287
Jack Thorne Avatar asked Jun 11 '15 04:06

Jack Thorne


2 Answers

It's because you have a non-optional property that doesn't have a default value.

var hero: JTHero

Is non-optional but it also has no value.

So, you can either make it optional by doing

var hero: JTHero?

Or you can create an init method and set the value in there.

Or create a default value...

var hero = JTHero()

There are many ways to do the latter.

like image 150
Fogmeister Avatar answered Sep 18 '22 15:09

Fogmeister


Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property’s definition.

Excerpt From: Apple Inc. The Swift Programming Language (Swift 2 Prerelease) iBooks. https://itun.es/us/k5SW7.l

Your GameScene class is not setting any initializers for its stored properties and does not define an init() method, and this is causing the error you're getting.

like image 39
bames53 Avatar answered Sep 17 '22 15:09

bames53