UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Project23: Errata

Forums > Books

In project 23, for the first of three parts to create enemies, the code in the book shows:

    func createEnemy(forceBomb: ForceBomb = .random) {
        let enemy = SKSpriteNode
        enemy = SKSpriteNode()
        var enemyType = Int.random(in: 0...6)
        if forceBomb == .never {
            enemyType = 1
        } else if forceBomb == .always {
            enemyType = 0
        }
        if enemyType == 0 {
           //bomb code here   
        } else {
            enemy = SKSpriteNode(imageNamed: "penguin")
        }
    }

There are two problems with the line

let enemy = SKSpriteNode

First, if you use 'let', then the the line enemy = SKSpriteNode(imageNamed: "penguin"). Second, the line as it is uses the assignment operator '=' but does not instantiate an instance of the SKSpriteNode class with '()' at the end.

The correct code when declaring that variable is:

var enemy: SKSpriteNode!

This makes the variable a 'var' that can be changed. A '!' is used to say that the variable will be defined below for sure.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.