Swift: Creating a Class

Creating a Class in Swift:

Classes can use to model everyday objects in the same way that structures can. And the syntax appears to be very similar. The basic syntax for creating a class in Swift is as follows:

class Name {
    // class definition

The class is created by using the class keyword and a class name. The class name is capitalised by convention. Classes contain both properties and methods, just like structures.

Assume we’re writing a programme to keep track of all the students at a school. Then, using a class, we can create a blueprint for this type of data.

Here’s an example of a Person class that represents a person:

class Person {
  var name: String ;
  var age: Int ;
  var gender: String ;
} ;

There are three properties in the Person class:

  • .name of the type String
  • .age is the type Int
  • .gender of the type String

We can also use Swift’s default property values to provide predefined values within the Person class:

class Person {
  var name = "" ;
  var age = 0 ;
  var gender = "" ;
} ;

When we create a new instance of Person, the .name property will be an empty string "", the .age property will be 0, and so on.

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: