Swift: Creating an Instance

Creating an Instance in Swift:

To refresh your memory, a class is nothing more than a template for creating objects. An instance of a class is commonly referred to as a “object.” A building blueprint, for example, is a class, and each house is an object, or instance of the class. Let’s see how we can create an instance of class in Swift.

We created a class to represent persons in the previous example:

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

We can now begin making Person instances using this blueprint. If we wanted to, we could make hundreds, if not thousands, of them! To model the teacher, we’ll create a Person instance.

To create an instance, use the following syntax:

var teacher = Person() ;

We’ve created a single Person instance and saved it to teacher. Using the dot syntax, .property, we can now access and edit the property values.

teacher.name = "John Dew" ;
teacher.age = 34 ;
teacher.gender = "Male" ;

We now know how to get a teacher out from a class.

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: