Swift Programming – Structures and Classes

In this tutorial you’ll learn about structures and classes in Swift. To follow along, it is recommended to have a Mac and the Xcode IDE installed on it. This tutorial makes use of the Xcode playground for compilation of the Swift codes. If you do not have a Mac, you may try using the open-source code editors which support different operating systems such as AtomSublimeText or VSCode.

Structures and Classes

You use structures and classes to contain your functionalities by defining properties and methods. It is recommended to use structures over classes wherever possible. However, if you need capabilities such as inheritance, type casting, deinitializers or reference counting, then it’s preferable to use classes.

// definition of a structure
struct AnimalDescription {
    var type: String = ""
    var breed: String?
    var numberOfLegs: Int = 0
}

// definition of a class
class Animal {
    var name: String
    var description = AnimalDescription()
}

Structure and Class Instances

You create instances of a structure and a class to describe specific characteristics.

let animalDescription = AnimalDescription()
let animal = Animal()

Accessing Properties

You use a dot(.) syntax to access the properties of a structure and a class.

print("My pet is a \(animalDescription.type) and her name is \(animal.name).")

Memberwise Initializers for Structure Types

Structures have a memberwise initializer generated automatically.

let animalDescription2 = AnimalDescription(type: "dog", breed: "German Shepherd", numberOfLegs: 4)
print("The animal type is a \(animalDescription2.type), of breed \(animalDescription2.breed ?? "") having \(animalDescription2.numberOfLegs) legs.")

Structures and Enumerations Are Value Types

Structures and enumerations are value types, which means that if these are assigned to variables or constants, their values are copied.

var animalDescription3 = animalDescription2
print("animalDescription3 type is a \(animalDescription3.type), of breed \(animalDescription3.breed ?? "") having \(animalDescription3.numberOfLegs) legs.")

animalDescription3.breed = "Golden Retriever"
print("animalDescription3 breed is \(animalDescription3.breed ?? "") and animalDescription2 breed is \(animalDescription2.breed ?? "")")

Classes Are Reference Types

Classes are reference types, which means that assigning a class to another, will reference the existing instance of that class.

var animal2 = animal
animal2.name = "Minou"

print("animal2's name \(animal2.name) animal's name \(animal.name)")

Identity Operators

Since classes are reference types, you can use the identical to (===) operator or not identical to (!==) operator to check if two classes are referencing the same instance.

if animal === animal2 {
    print("animal and animal2 are referencing the same instance")
}

Reference

https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html