Swift 4 - Cannot use mutating member on immutable value: '-' returns immutable value

I know I am early but I like to repeat the training with the next Swift version as a learning experience. So far the changes have been minimal and easily implemented. I am stuck on how to resolve the following from Chapter 12: Beginning Tile Maps page 326.

func move(target: CGPoint) {

guard let physicsBody = physicsBody else { return }

let newVelocity = (target - position).normalize() * PlayerSettings.playerSpeed

physicsBody.velocity = CGVector(point: newVelocity)

}

The line starting with let newVelocity creates the following error on the target - position portion of the statement.

Cannot use mutating member on immutable value: β€˜-’ returns immutable value

I looked at this a little longer and discovered that the issue relates to the result of (target - position) returning an immutable value which causes the .normalize() to syntax. As an actual fix needs to be implemented in the SKTUtils it was much simpler to simply use:

var newVelocity = (target - position)
newVelocity = newVelocity.normalize() * PlayerSettings.playerSpeed

1 Like

The function should actually be normalized() rather than normalize().

When you’re stuck like this, you can take the Final sample code and run it through the Swift converter and see what the difference is.

1 Like