swiftcocos2d-iphonecocos2d-swift

Swift Syntax Error : Type 'AnyObject' cannot be implicitly downcast


I used below code to create sprite in swift.

    var bg : CCSprite = CCSprite.spriteWithImageNamed("Default.png");
    bg.position = ccp(SW*0.5, SH*0.5)
    self.addChild(bg)

Please check image, its giving error for 1st line.enter image description here

Error : Type 'AnyObject' cannot be implicitly downcast to 'CCNode': did you mean to use 'as' to force downcast?

Is there any Cocos2d-Swift documents online ?


Solution

  • Just rewrite

    var bg : CCSprite = CCSprite.spriteWithImageNamed("Default.png")
    

    as

    var bg = CCSprite.spriteWithImageNamed("Default.png") as CCSprite
    

    Swift does not implicitly convert (in this case: AnyObject! to CCSprite), you have to add an explicit cast with as.