Swift attribute


Release date:2023-12-01 Update date:2023-12-08 Editor:admin View counts:258

Label:

Swift attribute

The Swift property associates a value with a specific class, structure, or enumeration.

Attributes can be divided into storage attributes and calculation attributes:

Storage attribute

Calculation attribute

Store constants or variables as part of an instance

Calculate (rather than store) a value

For classes and structures

For classes, structures, and enumerations

Storage and calculation properties are typically used for specific types of instances.

Properties can also be used directly for the type itself, which is called a type property.

In addition, a property watcher can be defined to monitor changes in property values to trigger a custom action. The property watcher can be added to a storage property written by itself or to a property inherited from the parent class.

Storage attribute

Simply put, a storage property is a constant or variable stored in an instance of a particular class or structure.

A storage property can be a variable storage property (with keywords var definition), or it can be a constant storage property (with keywords``let`` definition).

  • You can specify default values when defining storage properties

  • You can also set or modify the value of a storage property during construction, or even modify the value of a constant storage property

import Cocoa

struct Number
{
   var digits: Int
   let pi = 3.1415
}

var n = Number(digits: 12345)
n.digits = 67

print("\(n.digits)")
print("\(n.pi)")

The output of the above program execution is as follows:

67
3.1415

Consider the following code:

let pi = 3.1415

The pi in the code specifies the default value (pi = 3.1415) when defining the storage property, so whenever you instantiate the structure, it will notchange.

If you define a constant storage property, you will get an error if you try to modify it, as shown below:

import Cocoa

struct Number
{
    var digits: Int
    let numbers = 3.1415
}

var n = Number(digits: 12345)
n.digits = 67

print("\(n.digits)")
print("\(n.numbers)")
n.numbers = 8.7

The execution of the above procedures will report an error as follows:

error: cannot assign to property: 'numbers' is a 'let' constant
n.numbers = 8.7

Numbers’ is a constant and you can’t modify it.

Deferred storage attribute

A deferred storage property is a property whose initial value is calculated only when it is called for the first time.

Use before the property declaration lazy to indicate a deferred storageproperty.

Note: the deferred storage property must be declared as a variable using the``var`` keyword, because the value of the property may not be available until the instance construction is complete. A constant property must have an initial value before the construction process is complete, so it cannot be declared as a delay property.

Latency storage properties are generally used to:

  • Delay the creation of the object.

  • When the value of an attribute depends on other unknown classes

import Cocoa

class sample {
    lazy var no = number() // `var` Keywords are mandatory
}

class number {
    var name = "Runoob Swift tutorial"
}

var firstsample = sample()
print(firstsample.no.name)

The output of the above program execution is as follows:

Runoob Swift tutorial

Instantiate variable

If you have any experience with Objective-C, you should know that Objective-C provides two ways to store values and references for class instances. For properties, you can also use instance variables as the back-end storage of property values.

These theories are uniformly implemented by attributes in the Swift programming language. Properties in Swift have no corresponding instance variables, and the back-end storage of properties cannot be accessed directly. This avoids the trouble of access methods in different scenarios, and simplifies the definition of attributes into a single statement.

All information about attributes in a type– including naming, type, and memory management features– is defined in a unique place (in the type definition).

Calculation attribute

In addition to storing properties, classes, structures, and enumerations candefine calculated properties, which do not store values directly, but provide a getter to get the value, an optional setter to indirectly set the values of other properties or variables.

import Cocoa

class sample {
    var no1 = 0.0, no2 = 0.0
    var length = 300.0, breadth = 150.0

    var middle: (Double, Double) {
        get{
            return (length / 2, breadth / 2)
        }
        set(axis){
            no1 = axis.0 - (length / 2)
            no2 = axis.1 - (breadth / 2)
        }
    }
}

var result = sample()
print(result.middle)
result.middle = (0.0, 10.0)

print(result.no1)
print(result.no2)

The output of the above program execution is as follows:

(150.0, 75.0)
-150.0
-65.0

If you calculate the property’s setter if there is no parameter name defined to represent the new value, you can use the default name newValue .

Read-only calculation attribute

Only getter , setter is not the read-only calculation property.

The read-only calculation property always returns a value, which can be passed through the dot (.) Operator, but you cannot set a new value.

import Cocoa

class film {
    var head = ""
    var duration = 0.0
    var metaInfo: [String:String] {
        return [
            "head": self.head,
            "duration":"\(self.duration)"
        ]
    }
}

var movie = film()
movie.head = "Swift attribute"
movie.duration = 3.09

print(movie.metaInfo["head"]!)
print(movie.metaInfo["duration"]!)

The output of the above program execution is as follows:

Swift attribute
3.09

Note:

Must be used var keyword defines calculation properties, including read-only calculation properties, because their values are not fixed. let keyword is used only to declare constant properties, representing values that can no longer be modified after initialization.

Attribute viewer

The property watcher monitors and responds to changes in property values, calling the property watcher every time the property is set, even when the new value is the same as the current value.

You can add property watchers for storage properties other than deferred storage properties, or you can add property observers for inherited properties, including storage and calculation properties, by overloading properties.

Note: there is no need to add a property watcher for calculated properties that cannot be overloaded, because you can use the setter direct monitoring and changes in response values.

You can add one or all of the following observers to the property:

  • willSet Called before setting a new value

  • didSet Called immediately after the new value is set

  • willSet and didSet observer will not be called during property initialization

import Cocoa

class Samplepgm {
    var counter: Int = 0{
        willSet(newTotal){
            print("Counter: \(newTotal)")
        }
        didSet{
            if counter > oldValue {
                print("New additions \(counter - oldValue)")
            }
        }
    }
}
let NewCounter = Samplepgm()
NewCounter.counter = 100
NewCounter.counter = 800

The output of the above program execution is as follows:

Counter: 100
100 new additions
Counter: 800
700 new additions

Global and local variables

The patterns described by the calculated properties and property watchers can also be used for global and local variables.

Local variable

Global variable

A variable defined within a function, method, or closure.

Functions, methods, closures, or variables defined outside of any type.

Used to store and retrieve values.

Used to store and retrieve values.

Storage properties are used to get and set values.

Storage properties are used to get and set values.

It is also used to calculate attributes.

It is also used to calculate attributes.

Type attribute

Type properties are written in the outermost curly braces ({}) of the type as part of the type definition.

Use keywords static to define the type properties of the value type, keyword class to define type properties for the class.

struct Structname {
   static var storedTypeProperty = " "
   static var computedTypeProperty: Int {
      // Return an Int value here
   }
}

enum Enumname {
   static var storedTypeProperty = " "
   static var computedTypeProperty: Int {
      // Return an Int value here
   }
}

class Classname {
   class var computedTypeProperty: Int {
      // Return an Int value here
   }
}

Note: the computed type properties in the example are read-only, but you canalso define readable and writable computed type properties, similar to the syntax of the instance evaluation properties.

Gets and sets the value of the type property

Similar to the properties of an instance, type properties are also accessed through the dot operator (.) Let’s do it. However, type properties are obtained and set by the type itself, not by the instance. Examples are as follows:

import Cocoa

struct StudMarks {
   static let markCount = 97
   static var totalCount = 0
   var InternalMarks: Int = 0 {
      didSet {
         if InternalMarks > StudMarks.markCount {
            InternalMarks = StudMarks.markCount
         }
         if InternalMarks > StudMarks.totalCount {
            StudMarks.totalCount = InternalMarks
         }
      }
   }
}

var stud1Mark1 = StudMarks()
var stud1Mark2 = StudMarks()

stud1Mark1.InternalMarks = 98
print(stud1Mark1.InternalMarks)

stud1Mark2.InternalMarks = 87
print(stud1Mark2.InternalMarks)

The output of the above program execution is as follows:

97
87

Powered by TorCMS (https://github.com/bukun/TorCMS).