Since there is no debugger in a playground, I have been stuck trying to find the problem in this code. My errors are noted in comments below. Obviously the simulator does not run. Print statements are placed to try and see where the code stops interpreting…
I have tried comparing between the 5th edition code and what I have entered, and I can not see a difference (except where Xcode has suggested I make changes for swift 3?)
Any insight is greatly appreciated.
import Cocoa
print("foo 1")
struct Vector {
var x:Double
var y:Double
init(){
self.init(x:0,y:0)
}
init(x: Double, y:Double) {
self.x=x
self.y=y
}
func vectorByAddingVector(vector: Vector) -> Vector {
return Vector (x: x + vector.x,
y: y + vector.y)
}
static func +(left: Vector, right: Vector) -> Vector {
return left.vectorByAddingVector(vector: right)
}
static func *(left:Vector, right: Double) -> Vector {
return Vector (x:left.x * right, y:left.y * right)
}
static func +(left: Double, right: Vector) -> Vector {
return right * left
}
}
print("Foo 2")
class Particle {
var position: Vector
var velocity: Vector=Vector()
var acceleration: Vector=Vector()
init(position: Vector) {
self.position=position
self.velocity=Vector()
self.acceleration=Vector()
}
convenience init() {
self.init(position: Vector())
}
func tick(dt:TimeInterval) {
velocity=velocity+acceleration*dt
position=position+velocity*dt
position.y=max(0,position.y)
}
}
let gravity=Vector(x:0.0, y: 9.8)
let twoGs=gravity+gravity
let twoGsAlso=gravity * 2.0
print("Foo 3")
// Things break from here on down...prints do not work, and odd
// errors show up
class Simulation {
var particles: [Particle]=[]
var time: TimeInterval=0.0
func addParticle(particle: Particle) {
particles.append(particle)
}
func tick(dt: TimeInterval) {
for particle in particles {
particle.acceleration=particle.acceleration+gravity
particle.tick(dt: dt)
particle.acceleration=Vector()
particle.position.y
}
time += dt
particles=particles.filter { particle in
let live=particle.position.y>0.0
if !live {
print("Particle terminated at time: \(self.time)")
}
return live
}
) // ERROR: Expected expression
}
let simulation=Simulation()
let ball=Particle()
ball.acceleration=Vector(x:0,y:100) //ERROR: Expected declaration
Simulation.addParticle(ball)
while simulation.particles.count>0 && simulation.time<50 {
simulation.tick(dt: 1.0)
}
print("Foo 4")