Swift - Create class instance

Introduction

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:

Demo

class Car { 
    var color: String? 
    var maxSpeed = 80 
    /*from  w  w  w  . ja v a2s  . com*/
    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" 
print(b)

Result

Related Topic