Classes
Now that you have the beginnings of a robust vector type, let’s put it to work. Your 2D physics simulation will consist of two classes: Particle, which represents a single moving object within the simulation, and Simulation, which contains an array of Particle instances.
Classes are very similar to structures. They have a lot of the same features: initializers, properties, computed properties, and methods. They have a significant difference, however, which we will discuss once the simulation is up and running.
Start by defining the Particle class in your playground. The position is not important, as long as it is above or below (but not inside!) the Vector structure. A Particle has three Vector properties: position, velocity, and acceleration.
struct Vector { ... } class Particle { var position: Vector var velocity: Vector var acceleration: Vector }
Classes and structures differ significantly in terms of initializers. Most noticeably, classes do not have automatic initializers, so you will see a compiler error: Class 'Particle' has no initializers.
Fix this by adding an initializer to Particle:
class Particle { var position: Vector var velocity: Vector var acceleration: Vector init(position: Vector) { self.position = position self.velocity = Vector() self.acceleration = Vector() } }
You do not need to provide a parameter for every property in a class like you did in Vector’s init(x:y:). You just need to initialize everything. As with initializers for structures, a class’s initializer must initialize all of its properties before returning or performing any other tasks. By requiring this of initializers the Swift compiler guarantees that every instance is fully initialized before it is put to work.
Another approach is to give properties default values:
class Particle { var position: Vector var velocity: Vector = Vector() var acceleration: Vector = Vector() init(position: Vector) { self.position = position } }
In a simple case like this, there is not a clear benefit to either approach.
Designated and convenience initializers
Like structures, classes can have multiple initializers. At least one of them will be the designated initializer. Remember how you refactored Vector’s init() to call init(x:y:)? A designated initializer is an initializer which other, non-designated initializers – convenience initializers – must call. The rule of thumb with designated initializers is that they are typically the one with the most parameters. Most classes will only have one designated initializer.
The init(position:) initializer is the Particle class’s designated initializer. Add a convenience initializer:
class Particle { ... init(position: Vector) { self.position = position self.velocity = Vector() self.acceleration = Vector() } convenience init() { self.init(position: Vector()) } }
There is an exception to these designated initializer rules: required initializers, which you will see in Chapter 12.
Add an instance method
A particle has a position, velocity, and acceleration. It should also know a little about particle dynamics – specifically, how to update its position and velocity over time. Add an instance method, tick(_:), to perform these calculations.
class Particle { ... convenience init() { self.init(position: Vector()) } func tick(dt: NSTimeInterval) { velocity = velocity + acceleration * dt position = position + velocity * dt position.y = max(0, position.y) } }
The tick(_:) method takes an NSTimeInterval parameter, dt, the number of seconds to simulate. NSTimeInterval is an alias for Double.
Below the definition of Particle, define the Simulation class, which will have an array of Particle objects and its own tick(_:) method:
class Particle { ... } class Simulation { var particles: [Particle] = [] var time: NSTimeInterval = 0.0 func addParticle(particle: Particle) { particles.append(particle) } func tick(dt: NSTimeInterval) { for particle in particles { particle.acceleration = particle.acceleration + gravity particle.tick(dt) particle.acceleration = Vector() } time += dt } }
The Simulation class has no initializers defined since all of its properties have default values. The for-in loop iterates over the contents of the particles property. The tick(_:) method applies constant acceleration due to gravity to each of the particles before simulating them for the time interval.
Before you warm up the simulator and add a particle, add a line to evaluate particle.position.y. You will use this shortly with the playground’s Value History. Additionally, add some code to remove particles once they drop below y = 0:
class Simulation { ... func tick(dt: NSTimeInterval) { for particle in particles { particle.acceleration = particle.acceleration + gravity particle.tick(dt) particle.acceleration = Vector() particle.position.y } time += dt particles = particles.filter { particle in let live = particle.position.y > 0.0 if !live { println("Particle terminated at time \(self.time)") } return live } } }
The last chunk of code filters the particles array, removing any particles that have fallen to the ground. This is a closure, and it is OK if you do not understand it at this point. You will learn more about closures in Chapter 15.
Now you are ready to run the simulator. Create an instance of the simulator and a particle, add the particle to the simulation, and see what happens.
class Simulation { ... } let simulation = Simulation() let ball = Particle() ball.acceleration = Vector(x: 0, y: 100) simulation.addParticle(ball) while simulation.particles.count > 0 && simulation.time < 500 { simulation.tick(1.0) }
You should see the playground tally up (20 times) on a number of lines. If the playground runs the simulation continuously, you can stop it by commenting out the while loop. Select the three lines and hit Command-/ to toggle the comment marks:
// while simulation.particles.count > 0 && simulation.time < 500 { // simulation.tick(1.0) // }
Double-check your code against the listings above, in particular the lines that filter the particles array and the line that increments time.
Once you have the simulation running as expected, click the Variables View circle in the playground sidebar on the line that reads particle.position.y, as shown in Figure 3.1. A graph will appear, showing the Y values of the particle over time. The X axis on this graph represents iterations over time and not the X coordinate of the particle.
Figure 3.1 Graph data history of particle.position.y
Inheritance
Suppose you wanted to simulate a particle that had different behavior than the Particle class you have already implemented: a rocket that propels itself with thrust over a certain period of time. Since Particle already knows about physics, it would be natural to extend and modify its behavior through subclassing.
Define the Rocket class as a subclass of Particle.
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) } init(position: Vector, thrust: Double, thrustTime: NSTimeInterval) { self.thrust = thrust self.thrustTimeRemaining = thrustTime super.init(position: position) } }
The thrust property represents the magnitude of the rocket’s thrust. thrustTimeRemaining is the number of seconds that the thrust will be applied for. direction is the direction that the thrust will be applied in.
Take a minute to go through the initializers you just typed in. Which is the designated initializer? (Remember the rule of thumb about designated initializers?)
In order to guarantee that a class’s properties are initialized, initializers are only inherited if a subclass does not add any properties needing initialization. Thus, Rocket provides its own initializers and calls the superclass’s designated initializer.
Next you will override the tick(_:) method, which will do a little math to calculate the acceleration due to thrust and apply it before calling the superclass’s – Particle’s – tick(_:) method.
class Rocket: Particle { ... init(position: Vector, thrust: Double, thrustTime: NSTimeInterval) { self.thrust = thrust self.thrustTimeRemaining = thrustTime super.init(position: position) } override func tick(dt: NSTimeInterval) { if thrustTimeRemaining > 0.0 { let thrustTime = min(dt, thrustTimeRemaining) let thrustToApply = thrust * thrustTime let thrustForce = direction * thrustToApply acceleration = acceleration + thrustForce thrustTimeRemaining -= thrustTime } super.tick(dt) } }
Finally, create an instance of Rocket and add it to the simulation in place of the ball:
let simulation = Simulation()let ball = Particle()ball.acceleration = Vector(x: 0, y: 100)simulation.addParticle(ball)// let ball = Particle() // ball.acceleration = Vector(x: 0, y: 100) // simulation.addParticle(ball) let rocket = Rocket(thrust: 10.0, thrustTime: 60.0) simulation.addParticle(rocket)
The simulation will run for 70 “seconds” with these parameters. The Value History shows quite a different profile! (Figure 3.2)
Figure 3.2 The rocket’s Y position over time
Note that inheritance is one key differentiator between classes and structures: structures do not support inheritance.