Swift: Creating a Structure

Creating a Structure in Swift:

We can create our own data type with structures and use it to model everyday objects with their own distinct characteristics in Swift. The basic syntax for a structure is as follows:

struct Name {
 // Properties
}

The structure is created by using the struct keyword followed by the structure’s name. This name is capitalised by convention. The body is then defined inside the curly braces that follow, and this is where the structure’s unique properties and methods (which we’ll look at in a later exercise) are defined.

Here’s an example of a structure for car modelling:

struct Car {
  var name: String ;
  var speed: Int;
};

Car instead of Cars is a common singular name for structures. When we examine the Car structure more closely, we notice that it has two properties that resemble typed variables:

  • name typed as String.
  • speed typed as Int.

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: