Swift Tutorial How To Set & Get Swift Properties

Swift language provides setter and getter to the class properties to achieve Encapsulation.

The class contains properties and the instance of a class contains properties and variables. Usually, The properties of an object are set using the constructor. These will be initialized at the object creation level.

How do you set the properties of an object?

Using setters and getters allows you to set and get the property data after the instance is created.

This allows allowing the code to allow and modify through these.

This can be done by

  • Declare property variable as private
  • Add public set and get method or functions to the variable.

Swift Setter and Getter Property Example

the set method sets the property value of a class object, whereas the get method returns the property value of an object In this example,

class Employee {
  private var _id: Int = 0
  var id: Int {
    set { _id = newValue }
    get { return _id }
  }
}

var emp=Employee();

print(emp)
emp.id=10//10
print(emp.id)

Setters and getters are also used for compilation properties unlike with another programming language.

Conclusion

These setters and getters properties allow you to change the instance data once the object is created.