Swift / Object-Oriented Programming in Swift

Working with Class and Struct Instances

This tutorial aims to provide practical knowledge on working with class and struct instances in Swift. You'll learn how to create instances and manipulate their properties and met…

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Covers OOP concepts like classes, structures, and protocols in Swift.

Working with Class and Struct Instances

1. Introduction

Goal: In this tutorial, we aim to provide a practical and comprehensive understanding of how to work with class and struct instances in Swift.

Learning Outcomes: By the end of this tutorial, you will be able to:
- Understand class and struct instances in Swift
- Create instances of a class and struct
- Manipulate properties and methods of these instances

Prerequisites: This tutorial assumes you have a basic understanding of the Swift programming language. If not, I recommend going through Swift's official documentation.

2. Step-by-Step Guide

Understanding Class and Struct Instances

In Swift, both classes and structs can have properties and methods. An instance of a class or a struct is a realization of the class or struct. You can create an instance and manipulate its properties and call its methods.

Creating Instances

To create an instance of a class or a struct, you use the class or struct name followed by parentheses ().

Manipulating Properties

After creating an instance, you can access its properties using the dot . syntax, and you can modify them if they are not declared as constant with let.

Calling Methods

Methods can also be called on instances using the dot . syntax.

3. Code Examples

Example 1: Creating and Manipulating Instances

Here we'll create a simple struct and a class, create instances of them, and manipulate their properties.

// Defining a struct
struct Car {
    var color: String
    var brand: String
}

// Creating an instance of Car struct
var myCar = Car(color: "Red", brand: "BMW")
print(myCar.color) // prints "Red"

// Changing the property of the instance
myCar.color = "Blue"
print(myCar.color) // prints "Blue"

// Defining a class
class Phone {
    var model: String
    var brand: String

    init(model: String, brand: String) {
        self.model = model
        self.brand = brand
    }
}

// Creating an instance of Phone class
var myPhone = Phone(model: "iPhone 12", brand: "Apple")
print(myPhone.model) // prints "iPhone 12"

// Changing the property of the instance
myPhone.model = "iPhone 13"
print(myPhone.model) // prints "iPhone 13"

4. Summary

In this tutorial, we have learned about class and struct instances in Swift. We have seen how to create instances and manipulate their properties. We also looked at how to call methods on instances, though we didn't define any methods in our examples.

The next step in your learning journey could be exploring more about methods in classes and structs, including instance methods and type methods.

5. Practice Exercises

Exercise 1: Create a struct Book with properties title and author, and create an instance of it.

Exercise 2: Create a class Laptop with properties model and brand, and create an instance of it. Then, change the model of the instance.

Solutions:

Exercise 1:

struct Book {
    var title: String
    var author: String
}

var myBook = Book(title: "1984", author: "George Orwell")
print(myBook.title) // prints "1984"

Exercise 2:

class Laptop {
    var model: String
    var brand: String

    init(model: String, brand: String) {
        self.model = model
        self.brand = brand
    }
}

var myLaptop = Laptop(model: "MacBook Pro", brand: "Apple")
print(myLaptop.model) // prints "MacBook Pro"

myLaptop.model = "MacBook Air"
print(myLaptop.model) // prints "MacBook Air"

Continue practicing by creating more classes and structs, and creating instances of them. Try defining your own methods in those classes and structs, and call them on the instances. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help