I am new to coding and am trying to grasp how classes work in Swift. I wrote the follow code in Xcode 7.2.1 and receive an error 'Expected declaration' which points at the first character in line
myFirstCar.refuel().
import UIKit
class ViewController: UIViewController {
class Car {
var weight:Int = 1200
var gas:Int = 100
var maxGas:Int = 1000
func refuel() {
if gas < 900 {
gas += 100
} else {
gas += (maxGas - gas)
}
}
}
let myFirstCar = Car()
myFirstCar.refuel()
}
I would like this code to run the refuel() function inside the class.
I have looked around and believe this is a problem with the initialization of the function inside the Car class. I have tried initializing each variable in the class as well as initialize the function but I receive the same error code pointing at the same line.
I now think that I might be missing some vary fundamental rule when working with classes.
For instance, I do not know if the class ViewController: UIViewController is an issue because my class Car is contained within it and might be making the Car class a subclass of ViewController?
Like I said, I have looked around and found this code online which is essentially the same as mine.
class Tank {
class var bonusDamage: Double {
return Double(Upgrade.level) * 2.5
}
let baseDamage = 10.0
var damage: Double {
return self.baseDamage + Tank.bonusDamage
}
class func upgrade() {
Upgrade.level += 1
}
struct Upgrade {
static var level = 0
}
}
var tank = Tank()
println(tank.damage)
// 10.0
Tank.upgrade()
println(tank.damage)
// 12.5
Tank.upgrade()
println(tank.damage)
// 15.0
If I copy and paste the code into Xcode, it gives the same error 'Expected declaration' at the line:
println(tank.damage)
// 10.0
I guess my real problem is I do not understand this error. If someone could point me in a direction to look for an answer, that would be much appreciated!
Car.swift. You also seem to be using an old version of Swift, sinceprintlnhas been deprecated.