I have copied the code for Rocket class, however the compiler prints error: Designanted initializer cannot delegate(with ‘self.init’) on the first selected line and Cannot assign to ‘thrust’ in ‘self’. Could you please with this issue?
The code I have used(I copied it from the book without any changes):
class Rocket: Particle {
let thrust: Double
var thrustTimeRemaining: NSTimeInterval
let direction = Vector(x: 0, y: 1)
convenience init(thrust: Double, thrustTime: NSTimeInterval) {
self.init(position: Vector(), thrust: thrust, thrustTime: thrustTime)
}
// First line of error
init(position: Vector, thrust: Double, thrustTime: NSTimeInterval) {
// Second line of error
self.thrust = thrust
self.thrustTimeRemaining = thrustTime
self.init(position: position)
}
}
Somewhere above:
class Particle {
var position: Vector
var velocity: Vector
var acceleration: Vector
init(position: Vector) {
self.position = position
self.velocity = Vector()
self.acceleration = Vector()
}
convenience init() {
self.init(position: Vector())
}
func tick(dt: NSTimeInterval) {
velocity = velocity + acceleration * dt
position = position + velocity * dt
position.y = max(0, position.y)
}
}
// First line of error
init(position: Vector, thrust: Double, thrustTime: NSTimeInterval) {
// Second line of error
self.thrust = thrust
self.thrustTimeRemaining = thrustTime
self.init(position: position)
}
That last ‘self.init’ is the issue; it should be referencing the superclass via ‘[color=#FF0000]super[/color].init’:
// First line of error
init(position: Vector, thrust: Double, thrustTime: NSTimeInterval) {
// Second line of error
self.thrust = thrust
self.thrustTimeRemaining = thrustTime
super.init(position: position)
}
Fixing that takes care of everything.
By the way, I recommend skipping all the examples in Chapter 3, and instead read the section in the Swift language guide called Classes and Structures here:
The examples in Chapter 3 are confusing even if you know some physics, and if you don’t know any physics then they are a complete waste of time. In addition, the plot in the Playground is very misleading. Personally, I’ve abandoned using Playgrounds all together because I find using a Swift Command Line Tool a much better alternative.