Search code examples
swiftskspritenode

Can I make init on SKSpriteNode fail without crashing the app?


I am looping through the code below from a for loop. If certain circumstances are true I would like to "not" create the SKSpriteNode. Is there a specific return, i.e. -1, that I can call that would cause the SKSpriteNode to not be created, without crashing the app?

Or is this something that I need to figure out before creating it?

class GuessSlot : SKSpriteNode{
    var nodeIndex : Int
    var holdingGem : Bool = false

    init(color: SKColor, size: CGSize, width: CGFloat, iFactor: Int, guessBarRef: GuessBar){
        let skTexture = SKTexture(imageNamed: "gem_slot")
        self.nodeIndex = iFactor
        super.init(texture: skTexture, color: color, size: size)
        self.name = "slot"
        self.size.width     = size.width
        self.size.height    = size.width
        self.anchorPoint    = CGPoint(x: 0.5, y: 0.5)
        var indexSpacing    = (size.width * CGFloat(iFactor)) +
            ((size.height * 2) * CGFloat(iFactor)) + (size.width/2)
            indexSpacing += 10

        self.position = CGPoint(x: indexSpacing, y: guessBarRef.size.height/2)

        self.isHidden = false
        guessBarRef.addChild(self)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 }

Solution

  • Seems like you might want a failable initializer. This would return nil (means "nothing," kind of like -1).

    init?(color: SKColor, size: CGSize, width: CGFloat, iFactor: Int, guessBarRef: GuessBar) {
        if /* your condition here */ {
            return nil
        }
    }
    

    You'd then use it like this:

    if let slot = GuessSlot(color: ..., size: ..., width: ..., iFactor: ..., guessBarRef: ...) {
        /// `SKSpriteNode` has been created
    } else {
        /// won't crash app and `SKSpriteNode` is not created
    }