Creating Structs in Swift 🎯

beginner
9 min

Creating Structs in Swift 🎯

Welcome to another exciting tutorial at CodeYourCraft! Today, we're diving into the world of Swift, Apple's powerful and intuitive programming language. Today's topic is all about creating Structs, a fundamental building block in Swift.

Before we begin, let's clarify what a Struct is. In Swift, a Struct (short for Structure) is a user-defined data type used to organize complex data. It's similar to a Class, but with some key differences that we'll explore later.

Understanding Structs 📝

A Struct is a collection of properties, which can be of various data types. Here's a simple example of a Struct that represents a Point:

swift
struct Point { var x: Double var y: Double }

In this example, we've created a Point Struct with two properties: x and y, both of which are of type Double.

Creating and Initializing Structs 💡

You can create and initialize a Struct instance just like you would with a Class. Here's how you can create a new Point:

swift
let origin = Point(x: 0.0, y: 0.0)

In this example, we've created a new Point instance named origin and initialized it with x and y values of 0.0.

Struct Properties 📝

Struct properties can be defined as var for mutable properties or let for constant properties, just like in Classes. Here's an example with a constant color property:

swift
struct Rectangle { var x: Double var y: Double let color: String }

In this example, we've added a constant color property to our Rectangle Struct.

Methods in Structs 💡

Structs can also have methods, just like Classes. Here's an example of a Rectangle Struct with a method that calculates the area:

swift
struct Rectangle { var x: Double var y: Double let color: String func area() -> Double { return x * y } }

In this example, we've added a method named area to our Rectangle Struct. This method calculates and returns the area of the rectangle.

Structs vs Classes 📝

While both Structs and Classes can define properties and methods, there are some key differences:

  1. By default, Struct properties are copied when a new instance is created, while Class properties are referenced. This makes Structs value types and Classes reference types.
  2. Structs are considered lighter weight than Classes, as they don't support inheritance or deinitializers.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What is a Struct in Swift?

We've just scratched the surface of Structs in Swift. In the next lesson, we'll delve deeper into working with Structs, including the concept of Struct Associated Types. Until then, keep coding and learning! 🚀