Swift - Custom Type Class definition

Introduction

Classes in Swift look like this:

class Car { 

} 

Classes contain both properties and methods.

Properties are variables that are part of a class.

Methods are functions that are part of a class.

The Car class contains two properties: an optional String called color, and an Int called maxSpeed.

Property declarations is the same as variable declarations:

var color: String? 
var maxSpeed = 80 

Methods in a class look the same as functions, just inside the class definition.

Code that's in a method can access the properties of a class by using the self keyword.

self refers to the object that's currently running the code:

func description() -> String { 
    return "A \(self.color ?? "uncolored") vehicle" 
} 
func travel() { 
    print("Traveling at \(maxSpeed) kph") 
} 

You can omit the self keyword if it's obvious that the property is part of the current object.

Here, description uses the self keyword, while travel doesn't.

class Car { 
    var color: String? 
    var maxSpeed = 80 
    
    func description() -> String { 
        return "A \(self.color ?? "uncolored") vehicle" 
    } 
    func travel() { 
        print("Traveling at \(maxSpeed) kph") 
    } 
} 

Related Topics

Exercise