Swift - Create class instance


When you've defined a class, you can create instances of the class to work with.

Instances have their own copies of the class's properties and functions.

For example, to define an instance of the Vehicle class, you define a variable and call the class's initializer.

Once that's done, you can work with the class's functions and properties:


class Car { 
    var color: String? 
    var maxSpeed = 80 
    /*  w  w  w. j a v  a  2 s .  c o  m*/
    func description() -> String { 
        return "A \(self.color ?? "uncolored") vehicle" 
    func travel() { 
        print("Traveling at \(maxSpeed) kph") 
let a = Car() 
a.color = "Red" 
a.maxSpeed = 90 
a.travel() // prints "Traveling at 90 kph" 
var b = a.description() // = "A Red vehicle" 


Related Topic