Swift programming language Learning 11--enumerating global variables, local variables, and type properties

Source: Internet
Author: User



Global variables and local variables



The patterns described in computed properties and property monitors can also be used for global variables and local variables, which are variables defined outside of functions, methods, closures, or whatever types, and local variables are variables defined inside a function, method, or closure.






The global or local variables mentioned in the previous section are stored variables, similar to stored properties, which provide a specific type of storage space and agree to read and write.






In addition, both global and local scopes can define computed variables and define monitors for stored-type variables, and computed variables, like computed properties, return a computed value instead of a stored value, and the declaration format is the same.






Attention:






Global constants or variables are deferred, similar to deferred storage properties, except that global constants or variables do not need to be marked with the @lazy attribute.






Local-scope constants or variables do not delay calculations.






Type property



The properties of an instance belong to a particular type instance, each of which has its own set of property values each time the type is instantiated, and the attributes between the instances are independent of each other.






It is also possible to define attributes for the type itself, with only one by one copies of these properties, regardless of the number of instances of the type. Such a property is a Type property.






Type properties are used to define data that is shared by all instances of a particular type, such as a constant (like a static constant in C) that can be used by all instances, or a variable that all instances can access (just like a static variable in the C language).






For value types (which refer to structs and enumerations), you can define both the storage type and the computed Type property, and only the computed type attribute for the class.






A stored Type property of a value type can be a variable or constant, and a computed type property is defined as a variable property as the computed property of an instance.






Attention:






Unlike the storage properties of an instance, you must specify a default value for the stored Type property, because the type itself cannot be assigned a value for the Type property during initialization by using the constructor.






Type attribute syntax



In C or objective-c, static constants and static variables are defined by a specific type plus globalkeyword. In the Swift programming language, a type attribute is written as part of a type definition in curly braces of the outermost type, so its scope is within the range supported by the type.






Use Keywordstatic to define type properties for value types, keywordclass to define type properties for class. The following example shows the syntax for a stored-type and computed-type property:








struct SomeStructure {
    static var storedTypeProperty = "Some value."
    static var computedTypeProperty: Int {
    // here returns an Int value
     }
}
enum SomeEnumeration {
    static var storedTypeProperty = "Some value."
    static var computedTypeProperty: Int {
    // here returns an Int value
     }
}
class SomeClass {
    class var computedTypeProperty: Int {
    // here returns an Int value
     }
}






Attention:






The computed type attribute in the sample is read-only, but it is also possible to define a readable writable type property, similar to the syntax of an instance-computed property.






Gets and sets the value of the Type property



As with the properties of an instance, access to the Type property is done through the dot operator, but the Type property is obtained and set by the type itself, not by the instance. Example:








println (SomeClass.computedTypeProperty)
// print "42"
 
println (SomeStructure.storedTypeProperty)
// print "Somevalue."
SomeStructure.storedTypeProperty = "Another value."
println (SomeStructure.storedTypeProperty)
// print "Anothervalue."






The following example defines a struct that uses two storage type properties to represent the sound level values of multiple channels, each with an integer between 0 and 10 representing the sound level value.






The following diagram shows how to use two channels together to represent a stereo sound level value. When the level value of the channel is 0, no light is lit; when the channel level is 10, all lights are lit. In this figure, the left channel level is 9 and the right channel level is 7.












The channel model described above uses the Audiochannel structure to represent:








struct AudioChannel {
    static let thresholdLevel = 10
    static var maxInputLevelForAllChannels = 0
    var currentLevel: Int = 0 {
    didSet {
        if currentLevel> AudioChannel.thresholdLevel {
            // Set the new level value to the threshold
            currentLevel = AudioChannel.thresholdLevel
        }
        if currentLevel> AudioChannel.maxInputLevelForAllChannels {
            // Store the current level value as the new maximum input level
            AudioChannel.maxInputLevelForAllChannels = currentLevel
        }
     }
     }
}






The structure Audiochannel defines 2 storage type attributes to achieve these functions. The first is the Thresholdlevel, which represents the maximum upper threshold of the sound level, which is a constant of value 10 and is visible to all instances, assuming that the sound level is higher than 10, then the maximum upper value is 10 (see description later).






The second type attribute is the variable-stored-type attribute maxinputlevelforallchannels, which is used to represent the maximum value of the level value of all Audiochannel instances, with an initial value of 0.






Audiochannel also defines an instance store property named CurrentLevel, which represents the current level of the channel, with a value of 0 to 10.






The CurrentLevel property includes the Didset property monitor to check the value of the property after each new setting, such as the following two checks:






Assuming that the new value of CurrentLevel is greater than the agreed threshold Thresholdlevel, the property monitor limits the value of CurrentLevel to the threshold Thresholdlevel.



Assuming that the corrected CurrentLevel value is greater than the value in any arbitrary audiochannel instance before whatever, the property monitor saves the new value in the static property maxinputlevelforallchannels.



Attention:






The Didset property monitor sets CurrentLevel to a different value during the first check, but the property monitor is not called again.



The ability to use struct Audiochannel to create two channels Leftchannel and rightchannel that represent a stereo system:








var leftchannel = Audiochannel () var rightchannel = Audiochannel ()






Assuming the level of the left channel is set to 7, the type attribute maxinputlevelforallchannels is also updated to 7:








leftChannel.currentLevel = 7
println (leftChannel.currentLevel)
// print "7"
println (AudioChannel.maxInputLevelForAllChannels)
// print "7"
Assuming you try to set the level of the right channel to 11, the currentLevel of the right channel will be corrected to a maximum of 10, and at the same time the value of maxInputLevelForAllChannels will also be updated to 10:
 
rightChannel.currentLevel = 11
println (rightChannel.currentLevel)
// print "10"
println (AudioChannel.maxInputLevelForAllChannels)
// print "10" 






Swift programming language Learning 11--enumerating global variables, local variables, and type properties


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.