What are Properties in Swift ?

Yasir
Dev Genius
Published in
3 min readJun 10, 2020

--

In this article you will learn a depth knowledge of properties and how you could use getter , setter , computed and stored properties .

When you was making your own data type by creating a structure , inside that structure you was defining some variable and constants , those are called as properties .

Source :- http://www.thomashanning.com/properties-in-swift/

A important thing to note out is : Properties of a struct can only be change if it declares as a variable . You can give a default value in structure for any properties

There could be two type of Properties in Swift

  1. Stored Properties
  2. Computed Properties

While talking about stored properties , these could be a variable or constant which stores some value . And in computed properties , they were calculate the values instead of storing it . Stored properties could be a constant or a variable but the computed properties could only be variable .

As in computed properties , this only returns a calculation instead of storing it . This is called getter in computed properties .

Let’s see how we use getter and setter in our computed properties :

Image copied from Raywenderlich
Source :- Raywenderlich

Here’s what’s happening in this code:

  1. Because you want to include a setter, you now have to be explicit about which calculations comprise the getter and which the setter, so you surround each code block with curly braces and precede it with either get or set. This specificity isn’t required for read-only computed properties, as their single code block is implicitly a getter.
  2. You use the same code as before to get the computed value.
  3. For a setter, you usually have to make some kind of assumption. In this case, you provide a reasonable default value for the screen ratio.
  4. The formulas to calculate a height and width, given a diagonal and a ratio, are a bit deep. You could work them out with a bit of time, but I’ve done the dirty work for you and provided them here. The important parts to focus on are:
  5. a. The newValue constant lets you use whatever value was passed in during the assignment.b. Remember, the newValue is an Int, so to use it in a calculation with a Double, you must first convert it to a Double.c. Once you’ve done the calculations, you assign the height and width properties of the TV structure.

Key Points

  • Properties are variables and constants that are part of a named type.
  • Stored properties allocate memory to store a value.
  • Computed properties are calculated each time your code requests them and aren’t stored as a value in memory.
  • The static modifier marks a type property that’s universal to all instances of a particular type.

So this was all about Properties in swift , if you have any query feel free to ask in comment section .

My linkedIn :- linkedin.com/in/my-pro-file

--

--