Properties in Swift


In this Swift tutorial, you are going to learn about properties with code examples.

To understand properties, please make sure that you have already learned classes and structures.

A constant or a variable declared inside a class or structure is called a property. Properties in Swift associate values of a particular class or structure and are used to store values in constants or variables inside the class or structure.

Below is an example where you can see how we can create properties in a class:

class Student {

  // define properties 
  var firstName: String = ""
  var lastName: String = ""
  var age: Int = 0

  ... 
}

In the above example, we have defined three properties inside the Student class. These are given as below:

  • firstName: A property of string type
  • lastName: A property of string type
  • age: A property of integer type

Assigning and Accessing property values

To access the value of a property, we simply have to use a dot (.) after the object variable followed by the property name. Below is the syntax on how to access the value of a property:

object.property = VALUE

Below is an example of Swift property:

class Student {

  // defining three properties
  var firstName: String = ""
  var lastName: String = ""
  var age: Int = 0
}

// Creating object of the class Student
var student1 = Student()

// Assigning Values to properties
student1.firstName = "Maria"
student1.lastName = "Hernandez"
student1.age = 14

// Accessing the properties
print("First name: ", student1.firstName)
print("Last name: ", student1.lastName)
print("Age: ", student1.age)

The output of the above program:

First name: Maria
Last name: Hernandez
Age: 14

In the above example, we have assigned the value to the properties in the class Student and then accessed it with the object variable.

Below is another example where we have set the same property values in the class:

class Student {

  // defining three properties
  var firstName: String = "Maria"
  var lastName: String = "Hernandez"
  var age: Int = 14
}

// Creating object of the class Student
var student1 = Student()

// Accessing the properties
print("First name: ", student1.firstName)
print("Last name: ", student1.lastName)
print("Age: ", student1.age)

The output will be the same as the previous one. In this example, we have not assigned values outside of the class, we are providing the values directly inside the class. We are only accessing the property values.

Swift properties can be classified into two types. These are stored property and computed property.

Swift Stored Property

In this tutorial, all the examples above that we discussed are stored properties. Stored properties store the value for each instance.

Below is the example of a stored property in the class Sum:

class Calculate {
   // Define a stored property
   var num1 = 0
}

In the above example, the num1 is a stored property that stores a value for an instance of the class Calculate.

Swift Computed Property

In the case of a computed property, it calculates the value instead of storing an instance. That means, you don’t have to provide the value for a computed property, here you will calculate it inside curly brackets ( {…} ).

Below is an example of a computed property syntax:

class Calculate {
    
      ....
      // define a computed property
      var sum: Int {
        
        // calculate value
        num1 + num2
      }
}

In the above example, we have the property sum in the class Calculate. In our example, we are calculating the summation of two numbers variable.

Now see a proper example and run it:

class Calculate {
    var num1 = 0
    var num2 = 0
    
    // define a computed property
    var sum: Int {
        // calculate value
        num1 + num2
    }
}

var calculate1 = Calculate()
calculate1.num1 = 4
calculate1.num2 = 5

// Accessing the property value
print(calculate1.sum)

Output:

9

In the above example, we are calculating the addition of num1 and num2 in the property sum. You can notice that we have not assigned any value in the sum for the instance of the Calculate class. We are actually calculating the addition.

If you try to assign value to the sum it will show an error:

calculate1.sum = 67

You will see the error:

Cannot assign to property: 'sum' is a get-only property

Getters And Setters in Computed Properties

We can provide a getter and an optional setter to retrieve and set other properties and values indirectly.

The getter is used to return the computed value and the setter is used for modifying the computed value of the property.

To provide getter, we use the get keyword:

get {
   // Calculating value
}

The set keyword used to provide setter with the new value as the parameter:

set(newValue) {
   // Calculate with new value
}

Where newValue is a new value.

Below is an example of getter and setter in Swift property:

class Calculate {
 
    var num1 = 0
    var num2 = 0
    
    // Defining computed property
    
    var sum: Int {

      // retrieve value
      get {
        num1 + num2
      }
    
      // set new value to num1 and num2
      set(newValue) {
        num1 = (newValue + 5)
        num2 = (newValue + 10)
      }
    }
      
    
}


var object1 = Calculate()
object1.num1 = 5
object1.num2 = 6


// get value of sum
print("Sum value:", object1.sum)

// provide value of computed propert to modify
object1.sum = 10

print("New value of num1 property:", object1.num1)
print("New value of num2 property:", object1.num2)

Output:

Sum value: 11
New value of num1 property: 15
New value of num2 property: 20

In our program, we have defined a computed property sum inside the class Calculate.

The getter is used to get the sum of num1 and num2:

  get {
    num1 + num2
  }

And the setter to modify the value of num1 and num2:

  set(newValue) {
    num1 = (newValue + 5)
    num2 = (newValue + 10)
  }

Static properties

Till now, we see the examples where we have to use objects to assign and access their properties. However, it is possible to assign and access properties values without creating the object of a class. For this, we have to create the static property.

You can directly access the property value without creating an object. You can also modify and provide new value to property without creating the object of the class.

You can create properties that belong to a type, rather than to instances of a type in order to organize data more effectively. These types of properties are called static properties.

Define a static property

In Swift, the static keyword is used to define a static property. After the static keyword, you just need to create the property as you do regularly. Below is the example of creating a static property inside the Employee class:

class Employee {
    // Define a static property
    static var name = "Charlotte"
}

In the above example, the name property is a static property. I told you earlier, you can access the value of a static property without creating an object. So below is how you can access the value of name property:

print(Employee.name)
Employee.name = "Emma"

Now let’s see the complete code example below where we have created a static property, accessed it and modified it:

class Employee {
    // Define a static property
    static var name = "Charlotte"
}

// Access value of the property
print(Employee.name)

// Modify property value
Employee.name = "Emma"

// Access property value after modifying it
print(Employee.name)

Output:

Charlotte
Emma

In the above example, you can see that we have not created an object of the class Employee, but are still able to access and modify the property value. It is possible because the property name is a static property.