属性 (Properties)
1.存储属性
存储在类或结构体的实例中的一个变量或常量,可以在定义的时候赋值,也可以在构造过程时候赋值
-
- structFixedLengthRange{
- varfirstValue:Int
- letlength:Int
- }
- varrangeOfThreeItems=FixedLengthRange(firstValue:0,length:3)
- //therangerepresentsintegervalues0,1,and2
- rangeOfThreeItems.firstValue=6
- //therangenowrepresentsintegervalues6,7,and8
2.常量
创建一个结构体的实例并赋值给一个常量,就无法再修改实例的任何属性了,即使有定义变量属性,因为结构体属于值类型,当值类型的实例被声明为常量的时候,所有的属性也就成了常量,跟引用类型的类不一样,类赋值给常量后,仍然可以修改实例的属性
letrangeOfFourItems=FixedLengthRange(firstValue:0,0); background-color:inherit">length:4)
-
- rangeOfFourItems.firstValue=6
- //thiswillreportanerror,eventhoughtfirstValueisavariableproperty
3.延迟存储属性
当第一次被调用的时候才会计算其初始值,使用@lazy标志,属性的值在实例构造完成之前可能为空,而常量要求构造完成之前必须有初始值,所以延迟属性必须是变量
//DataImporter在初始化的时候需要消耗不少时间,因为可能要打开文件并读取文件内容,所以在创建DataManager的时候不需要创建DataImporter实例,而是当用到才创建
- classDataImporter{
- /*
- DataImporterisaclasstoimportdatafromanexternalfile.
- Theclassisassumedtotakeanon-trivialamountoftimetoinitialize.
- */
- varfileName="data.txt"
- //theDataImporterclasswouldprovidedataimportingfunctionalityhere
-
- classDataManager{
- @lazyvarimporter=DataImporter()
- vardata=String[]()
- //theDataManagerclasswouldprovidedatamanagementfunctionalityhere
- letmanager=DataManager()
- manager.data+="Somedata"
- manager.data+="Somemoredata"
- //theDataImporterinstancefortheimporterpropertyhasnotyetbeencreated
4.计算属性
计算属性不直接存储值,提供一个getter来获取,可选的setter来设置
structPoint{
- varx=0.0,y=0.0
- structSize{
- varwidth=0.0,height=0.0
- }
- structRect{
- varorigin=Point()
- varsize=Size()
- varcenter:Point{
- get{
- letcenterX=origin.x+(size.width/2)
- letcenterY=origin.y+(size.height/2)
- returnPoint(x:centerX,0); background-color:inherit">y:centerY)
- set(newCenter){
- origin.x=newCenter.x-(size.width/2)
- origin.y=newCenter.y-(size.height/2)
- varsquare=Rect(origin:Point(x:0.0,0); background-color:inherit">y:0.0),
- size:Size(width:10.0,0); background-color:inherit">height:10.0))
- letinitialSquareCenter=square.center
- square.center=Point(x:15.0,0); background-color:inherit">y:15.0)
- println("square.originisnowat((square.origin.x),(square.origin.y))")
- //prints"square.originisnowat(10.0,10.0)"
5.便捷setter声明
如果setter没有定义参数名,则使用默认名称 newValue
structAlternativeRect{
- set{
- origin.x=newValue.x-(size.width/2)
- origin.y=newValue.y-(size.height/2)
- }
6.只读计算属性
只有getter没有setter的计算属性,总是返回一个值,通过点运算符访问,不能赋新值
structCuboid{
- varwidth=0.0,height=0.0,depth=0.0
- volume:Double{
- returnwidth*height*depth
- letfourByFiveByTwo=Cuboid(width:4.0,0); background-color:inherit">height:5.0,0); background-color:inherit">depth:2.0)
- println("thevolumeoffourByFiveByTwois(fourByFiveByTwo.volume)")
- //prints"thevolumeoffourByFiveByTwois40.0"
7.属性监视器
监控属性值的变化,在属性被设置新值的时候调用,即使新值与原有相同,可以为延迟属性添加监视器,不需要为无法重载的计算属性添加监视器,因为可以通过setter直接监控
wilSet 在设置新值前调用
didSet 新的值被设定后调用
willSet会将新值作为固定参数传入,如果不指定参数,默认使用newValue,didSet会将就值作为参数传入,不指定的话默认参数名为oldValue,如果在didSet监视器为属性设值,那这个值会替换监视器之前设置的值
willSet和didSet监视器不会在属性初始化的时候调用,只会在属性初始化之后的其他地方比如被设置的时候调用
classStepCounter{
- totalSteps:Int=0{
- willSet(newTotalSteps){
- println("AbouttosettotalStepsto(newTotalSteps)")
- didSet{
- iftotalSteps>oldValue{
- println("Added(totalSteps-oldValue)steps")
- letstepCounter=StepCounter()
- stepCounter.totalSteps=200
- //AbouttosettotalStepsto200
- //Added200steps
- stepCounter.totalSteps=360
- //AbouttosettotalStepsto360
- //Added160steps
- stepCounter.totalSteps=896
- //AbouttosettotalStepsto896
- //Added536steps
8.全局变量和局部变量
全局变量是相对于全局的,在函数,方法,闭包或任何类型之外定义的变量,局部变量是在函数,方法或闭包内部定义的变量,全局变量跟延迟存储属性一样,但不需要@lazy修饰
9.类型属性
类型属性语法 使用关键字static定义值类型的类型属性,class定义类
structSomeStructure{
- staticvarstoredTypeProperty="Somevalue."
- staticvarcomputedTypeProperty:Int{
- //returnanIntvaluehere
- enumSomeEnumeration{
- classSomeClass{
- classvarcomputedTypeProperty:Int{
- //returnanIntvaluehere
- }
获取和设置类型属性的值
类型属性的访问是通过点运算符操作
println(SomeClass.computedTypeProperty)
- //prints"42"
-
- println(SomeStructure.storedTypeProperty)
- //prints"Somevalue."
- SomeStructure.storedTypeProperty="Anothervalue."
- println(SomeStructure.storedTypeProperty)
- //prints"Anothervalue."
以下是另一个比较完整的例子
structAudioChannel{
- staticletthresholdLevel=10
- staticvarmaxInputLevelForAllChannels=0
- currentLevel:Int=0{
- didSet{
- ifcurrentLevel>AudioChannel.thresholdLevel{
- //capthenewaudioleveltothethresholdlevel
- currentLevel=AudioChannel.thresholdLevel
- ifcurrentLevel>AudioChannel.maxInputLevelForAllChannels{
- //storethisasthenewoverallmaximuminputlevel
- AudioChannel.maxInputLevelForAllChannels=currentLevel
- varleftChannel=AudioChannel()
- varrightChannel=AudioChannel()
- leftChannel.currentLevel=7
- println(leftChannel.currentLevel)
- //prints"7"
- println(AudioChannel.maxInputLevelForAllChannels)
- rightChannel.currentLevel=11
- println(rightChannel.currentLevel)
- //prints"10"
- //prints"10"
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|