YouTip LogoYouTip

Swift Properties

Swift properties associate values with a specific class, structure, or enumeration.\\n\\nProperties can be divided into stored properties and computed properties:\\n\\n| **Stored Properties** | **Computed Properties** |\\n| --- | --- |\\n| Store constants or variables as part of an instance | Compute (rather than store) a value |\\n| Used for classes and structures | Used for classes, structures, and enumerations |\\n\\nStored properties and computed properties are typically used for instances of a specific type.\\n\\nProperties can also be used directly on the type itself, these properties are called type properties.\\n\\nAdditionally, you can define property observers to monitor changes in a property's value, thereby triggering a custom operation. Property observers can be added to stored properties you write yourself, or to properties inherited from a parent class.\\n\\n* * *\\n\\n## Stored Properties\\n\\nSimply put, a stored property is a constant or variable stored as part of a specific class or structure instance.\\n\\nStored properties can be variable stored properties (defined with the keyword var) or constant stored properties (defined with the keyword let).\\n\\n* You can specify a default value when defining a stored property\\n\\n* You can also set or modify the value of a stored property during construction, even modifying the value of a constant stored property\\n\\nimport Cocoastruct Number{ var digits: Int let pi = 3.1415}var n = Number(digits: 12345) n.digits = 67print("\\\\(n.digits)")print("\\\\(n.pi)")\\nThe output of the above program execution is:\\n\\n673.1415\\nConsider the following code:\\n\\nlet pi = 3.1415\\nIn the code, pi specifies a default value when defining the stored property (pi = 3.1415), so no matter when you instantiate the structure, it will not change.\\n\\nIf you define a constant stored property, attempting to modify it will result in an error, as shown below:\\n\\nimport Cocoastruct Number{ var digits: Int let numbers = 3.1415}var n = Number(digits: 12345) n.digits = 67print("\\\\(n.digits)")print("\\\\(n.numbers)") n.numbers = 8.7\\nIn the above program, execution will report an error, as shown below:\\n\\nerror: cannot assign to property: 'numbers' is a 'let' constant n.numbers = 8.7\\nThis means 'numbers' is a constant, and you cannot modify it.\\n\\n* * *\\n\\n## Lazy Stored Properties\\n\\nA lazy stored property is a property whose initial value is not calculated until the first time it is called.\\n\\nUse the **lazy** keyword before the property declaration to indicate a lazy stored property.\\n\\n> Note:\\n> \\n> You must declare lazy stored properties as variables (using the `var` keyword), because the property's value might not be retrieved until after instance construction completes. Constant properties must always have an initial value before construction completes, and therefore cannot be declared as lazy properties.\\n\\nLazy stored properties are typically used for:\\n\\n* Delaying the creation of an object.\\n\\n* When the property's value depends on other unknown classes\\n\\nimport Cocoaclass sample { lazy var no = number() // `var` keyword is required}class number { var name = "Tutorial Swift Tutorial"}var firstsample = sample()print(firstsample.no.name)\\nThe output of the above program execution is:\\n\\nTutorial Swift Tutorial\\n\\n* * *\\n\\n## Instance Variables\\n\\nIf you have Objective-C experience, 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 backing storage for property values.\\n\\nThe Swift programming language unifies these concepts into properties. Properties in Swift do not have corresponding instance variables, and the backing storage of a property cannot be accessed directly. This avoids the confusion of access methods in different contexts, and also simplifies property definition into a single statement.\\n\\nAll information about a property in a typeβ€”including naming, type, and memory management characteristicsβ€”is defined in one unique place (the type definition).\\n\\n* * *\\n\\n## Computed Properties\\n\\nIn addition to stored properties, classes, structures, and enumerations can define _computed properties_, which do not store a value directly, but instead provide a getter to retrieve a value, and an optional setter to indirectly set the values of other properties or variables.\\n\\nimport Cocoaclass 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)\\nThe output of the above program execution is:\\n\\n(150.0, 75.0)-150.0-65.0\\nIf the setter of a computed property does not define a parameter name for the new value, the default name newValue can be used.\\n\\n* * *\\n\\n## Read-Only Computed Properties\\n\\nA computed property with only a getter and no setter is a read-only computed property.\\n\\nA read-only computed property always returns a value, which can be accessed via the dot (.) operator, but cannot be set to a new value.\\n\\nimport Cocoaclass film { var head = "" var duration = 0.0 var metaInfo: [String:String] { return [ "head": self.head, "duration":"\\\\(self.duration)" ] }}var movie = film() movie.head = "Swift Properties" movie.duration = 3.09print(movie.metaInfo!)print(movie.metaInfo!)\\nThe output of the above program execution is:\\n\\nSwift Properties3.09\\n> Note:\\n> \\n> \\n> You must use the `var` keyword to define computed properties, including read-only computed properties, because their values are not fixed. The `let` keyword is only used to declare constant properties, indicating values that cannot be modified after initialization.\\n\\n* * *\\n\\n## Property Observers\\n\\nProperty observers monitor and respond to changes in a property's value. Property observers are called every time a property's value is set, even if the new value is the same as the current value.\\n\\nYou can add property observers to any stored property except lazy stored properties, and you can also add property observers to inherited properties (including both stored and computed properties) by overriding the property.\\n\\n> Note:\\n> \\n> You do not need to add property observers to computed properties that cannot be overridden, because you can directly monitor and respond to value changes through their setter.\\n\\nYou can add either or both of the following observers to a property:\\n\\n* `willSet` is called just before the value is set\\n* `didSet` is called immediately after the new value is set\\n* willSet and didSet observers are not called during property initialization\\n\\nimport Cocoaclass Samplepgm { var counter: Int = 0{ willSet(newTotal){ print("Counter: \\\\(newTotal)") } didSet{ if counter > oldValue { print("Increment \\\\(counter - oldValue)") } } }}let NewCounter = Samplepgm()NewCounter.counter = 100NewCounter.counter = 800\\nThe output of the above program execution is:\\n\\nCounter: 100Increment 100Counter: 800Increment 700\\n\\n* * *\\n\\n## Global and Local Variables\\n\\nThe patterns described for computed properties and property observers can also be applied to global and local variables.\\n\\n| **Local Variables** | **Global Variables** |\\n| --- | --- |\\n| Variables defined inside functions, methods, or closures. | Variables defined outside of functions, methods, closures, or any type. |\\n| Used to store and retrieve values. | Used to store and retrieve values. |\\n| Stored properties are used to get and set values. | Stored properties are used to get and set values. |\\n| Also used for computed properties. | Also used for computed properties. |\\n\\n* * *\\n\\n## Type Properties\\n\\nType properties are written as part of the type definition, within the outermost curly braces ({}) of the type.\\n\\nUse the keyword static to define type properties for value types, and the keyword class to define type properties for classes.\\n\\nstruct Structname { static var storedTypeProperty = " " static var computedTypeProperty: Int { // Returns an Int Value here }}enum Enumname { static var storedTypeProperty = " " static var computedTypeProperty: Int { // Returns an Int Value here }}class Classname { class var computedTypeProperty: Int { // Returns an Int Value here }}\\n> Note:\\n> \\n> The computed type properties in the examples are read-only, but you can also define read-write computed type properties with syntax similar to that of instance computed properties.\\n\\n* * *\\n\\n## Getting and Setting Type Properties\\n\\nSimilar to instance properties, type properties are accessed using the dot (.) operator. However, type properties are queried and set on the type itself, not on an instance. An example is as follows:\\n\\nimport Cocoastruct 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 = 98print(stud1Mark1.InternalMarks) stud1Mark2.InternalMarks = 87print(stud1Mark2.InternalMarks)\\nThe output of the above program execution is:\\n\\n9787
← Swift MethodsSwift Classes β†’