Swift: Default Property Values

Default Property Values in Swift:

We should be able to create customised instances of a structure now that we know how to create one. But, if we’re going to create a lot of instances, do we really need to customise each one? In some cases, we may discover that the instance’s properties do not always require a unique value and that some common values can be reused. So, we use default property values of structure in Swift.

To set values for properties inside our structures, we’ll use Swift’s concept of default property values. When we get to creating instances, this will save us time.

struct Car {
  var name = "" ;
  var speed = 0 ;
};

It’s worth noting that assigning default values uses the same syntax as assigning values to variables. When we create an instance of Car later, the name value will be "" and the speed value will be 0.

Take a look at our introductory structures GIF, as an example. Our building blueprint has default property values: two floors and a triangular roof, as shown in the GIF. We kept some values and changed others as we created new building instances.

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: