Property
Apple Official document Properties
Apple Official document translation Properties
A property can associate a value with a specific class, struct, or enumeration.
Store Properties
struct FixedLengthRange { var firstValue: Int let length: Int}var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3)rangeOfThreeItems.firstValue = 6// the range now represents integer values 6, 7, and 8
Storage properties for a constant struct instance
let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4)// this range represents integer values 0, 1, 2, and 3rangeOfFourItems.firstValue = 6// this will report an error, even though firstValue is a variable property
Deferred storage properties
The initial value of a deferred store property is evaluated when it is first used. Label the ==lazy== modifier before the declaration to represent a deferred storage property. and the declaration must be a variable.
class DataImporter { //DataImporter is a class to import data from an external file. //The class is assumed to take a non-trivial amount of time to initialize. var fileName = "data.txt" // the DataImporter class would provide data importing functionality here} class DataManager { lazy var importer = DataImporter() var data = [String]() // the DataManager class would provide data management functionality here} let manager = DataManager()manager.data.append("Some data")manager.data.append("Some more data")// the DataImporter instance for the importer property has not yet been created
print(manager.importer.fileName)// the DataImporter instance for the importer property has now been created// prints "data.txt"
Storing attributes and instance variables
The Swift property does not have an instance variable corresponding to it, and the backing store for the property cannot be accessed directly.
Calculated properties
struct Point { var x = 0.0, y = 0.0}struct Size { var width = 0.0, height = 0.0}struct Rect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set(newCenter) { origin.x = newCenter.x - (size.width / 2) origin.y = newCenter.y - (size.height / 2) } }}var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0))let initialSquareCenter = square.centersquare.center = Point(x: 15.0, y: 15.0)print("square.origin is now at (\(square.origin.x), \(square.origin.y))")// prints "square.origin is now at (10.0, 10.0)"
Shorthand set (setter) Declaration
If the set of a computed property does not define a name for the value that will be set, then he will be named NewValue by default.
struct AlternativeRect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set { origin.x = newValue.x - (size.width / 2) origin.y = newValue.y - (size.height / 2) } }}
Read-only computed properties
A computed property with a reader but no setting is called a read-only computed property.
Remove the Get keyword and his large expansion number to simplify the declaration of the read-only computed attribute:
struct Cuboid { var width = 0.0, height = 0.0, depth = 0.0 var volume: Double { return width * height * depth }}let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0)print("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)")// prints "the volume of fourByFiveByTwo is 40.0"
Attribute Observer
The attribute observer observes and responds to changes in the property values.
- The willset is called before the value is stored.
The willset is called before the value is stored.
class StepCounter {var totalSteps: Int = 0 { willSet(newTotalSteps) { print("About to set totalSteps to \(newTotalSteps)") } didSet { if totalSteps > oldValue { print("Added \(totalSteps - oldValue) steps") } }}}let stepCounter = StepCounter()stepCounter.totalSteps = 200// About to set totalSteps to 200// Added 200 stepsstepCounter.totalSteps = 360// About to set totalSteps to 360// Added 160 stepsstepCounter.totalSteps = 896// About to set totalSteps to 896// Added 536 steps
Global variables and local variablesThe ability to calculate attributes and observe attributes is also valid for global variables and local variables.
Type propertyYou can define a property that belongs to the type itself, not a property of one instance of that type. This property has only one copy, regardless of how many instances of the class you created. Such a property is called a type attribute.
Refer to the documentation for details.
Type attribute syntax==static== keyword to open a Type property
struct SomeStructure {static var storedTypeProperty = "Some value."static var computedTypeProperty: Int { return 1}}enum SomeEnumeration {static var storedTypeProperty = "Some value."static var computedTypeProperty: Int { return 6}}class SomeClass {static var storedTypeProperty = "Some value."static var computedTypeProperty: Int { return 27}class var overrideableComputedTypeProperty: Int { return 107}}
Querying and setting type propertiesThe type attribute is queried and set in the class, not an instance of this type.
print(SomeStructure.storedTypeProperty)// prints "Some value."SomeStructure.storedTypeProperty = "Another value."print(SomeStructure.storedTypeProperty)// prints "Another value."print(SomeEnumeration.computedTypeProperty)// prints "6"print(SomeClass.computedTypeProperty)// prints "27"
The following example uses two storage-type attributes as part of a structure that models an audio measurement table for a digital audio channel. Each channel has a digital audio level between 0 and 10.
The illustration below shows how this audio channel can be combined to model a stereo audio meter. When the channel's audio level is 0, the corresponding channel's light will not be lit. When the level is 10, all the lights on this channel will be lit. In this illustration, the current level of the left channel is 9 and the current level of the right channel is 7:
struct AudioChannel { static let thresholdLevel = 10 static var maxInputLevelForAllChannels = 0 var currentLevel: Int = 0 { didSet { if currentLevel > AudioChannel.thresholdLevel { // cap the new audio level to the threshold level currentLevel = AudioChannel.thresholdLevel } if currentLevel > AudioChannel.maxInputLevelForAllChannels { // store this as the new overall maximum input level AudioChannel.maxInputLevelForAllChannels = currentLevel } } }}var leftChannel = AudioChannel()var rightChannel = AudioChannel()leftChannel.currentLevel = 7print(leftChannel.currentLevel)// prints "7"print(AudioChannel.maxInputLevelForAllChannels)// prints "7"rightChannel.currentLevel = 11print(rightChannel.currentLevel)// prints "10"print(AudioChannel.maxInputLevelForAllChannels)// prints "10"
The Swift4 property, the document code.