NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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.

1      

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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.