Swift Basics: Classes

Learn about classes in the Swift Programming Language

Stanley Miller 
2 min readJan 24, 2023

Classes in Swift are a way to define custom types that can be used to create objects. These objects can have their own properties, which are like variables that store information, and methods, which are like functions that can perform actions.

Here’s an example of a class in Swift that represents a fictional character in a game:

In this example, we have a class called Character that has three properties: name, health, and attackPower. These properties are defined using the var keyword and have a type (e.g. String, Int).

We also have an initializer, which is a special method that’s called when we create a new object of this class. The initializer is responsible for setting the values of the object’s properties. In this case, we use the self keyword to refer to the current object and assign the values of the parameters (name, health, and attackPower) to the object's properties.

Finally, we have a method called attack, which takes a target Character object as a parameter and reduces its health by the attack power of the current Character object.

Now that we have our Character class defined, we can create objects of this type using the init initializer:

We can then use these objects to perform actions and access their properties:

Classes are a powerful tool in Swift, as they allow us to define custom types with their own properties and methods. They are often used to represent real-world objects or concepts, like characters in a game or items in a shopping cart.

🤟 If this article helps you, help someone else and share it.

🌮 BuyMeATaco if you’re in a generous mood.

🚀 @MrMkeItHappen

--

--