Methods in Structs/Classes 🚀

beginner
20 min

Methods in Structs/Classes 🚀

Welcome to our Swift Tutorial on Methods in Structs and Classes! Let's dive into the world of Swift, where we'll learn how to create powerful and reusable functions for our custom data structures. 🎯

What are Methods? 📝

In Swift, methods are functions that are defined within a struct or class to perform specific actions on the data they contain. They help in encapsulating related functionalities, making our code cleaner and easier to manage. 💡

Structs vs Classes 💡

Before we dive into methods, let's quickly recap the difference between structs and classes.

  • Structs: Structures are value types that hold multiple properties and methods. They are passed by value, meaning that the entire struct is copied when it's passed to a function or assigned to a variable.
  • Classes: Classes are reference types, also with properties and methods. They are passed by reference, meaning that the memory location of the class is shared.

Creating a Method in a Struct 📝

Let's create a simple struct and define a method within it.

swift
struct Point { var x: Double var y: Double func distanceFromOrigin() -> Double { return sqrt(x * x + y * y) } }

In the example above, we have created a struct called Point with properties x and y. We have also defined a method called distanceFromOrigin() that calculates the distance between the point and the origin.

Creating a Method in a Class 📝

Creating a method in a class is very similar to creating one in a struct. Here's an example:

swift
class Rectangle { var width: Double var height: Double func area() -> Double { return width * height } }

In this example, we have created a class called Rectangle with properties width and height. We have also defined a method called area() that calculates the area of the rectangle.

Calling Methods 📝

To call a method in Swift, we use the dot notation. Here's how you can call the methods we created earlier:

swift
let origin = Point(x: 0, y: 0) let myPoint = Point(x: 3, y: 4) let originDistance = origin.distanceFromOrigin() // returns 0.0 let myPointDistance = myPoint.distanceFromOrigin() // returns 5.0 let myRectangle = Rectangle(width: 5, height: 10) let myRectangleArea = myRectangle.area() // returns 50.0

Method Overloading 💡

Method overloading in Swift allows us to define multiple methods with the same name but different parameters. This allows us to perform different actions based on the parameters passed.

Method Types 💡

Methods in Swift can be of different types:

  • Instance Methods: These methods are called on instances of a struct or class.
  • Type Methods: These methods are called on the struct or class type itself.
  • Static Methods: These methods are called using the name of the struct or class, without the need to create an instance.

Quiz 🎯

Quick Quiz
Question 1 of 1

What are methods in Swift?

Quick Quiz
Question 1 of 1

What is the difference between structs and classes in Swift?