Swift4 基礎(chǔ)部分: Properties

本文是學(xué)習(xí)《The Swift Programming Language》整理的相關(guān)隨筆蓖康,基本的語法不作介紹铐炫,主要介紹Swift中的一些特性或者與OC差異點。

系列文章:

常量的結(jié)構(gòu)體實例的屬性(Stored Properties of Constant Structure Instances)

If you create an instance of a structure and assign that 
instance to a constant, you cannot modify the instance’s 
properties, even if they were declared as variable 
properties:
  • 常量的結(jié)構(gòu)體實例的屬性即使是var修飾也不能更改它的值

例子:

struct FixedLengthRange{
    var firstValue:Int
    let length:Int
}

let rangeOfFourItems = FixedLengthRange(firstValue:0,length:4)
rangeOfFourItems.firstValue = 6;

編譯錯誤:

error: MyPlayground.playground:527:29: error: cannot assign to property: 'rangeOfFourItems' is a 'let' constant
rangeOfFourItems.firstValue = 6;
~~~~~~~~~~~~~~~~            ^

MyPlayground.playground:526:1: note: change 'let' to 'var' to make it mutable
let rangeOfFourItems = FixedLengthRange(firstValue:0,length:4)
^~~

原因:

Because rangeOfFourItems is declared as a constant (with 
the let keyword), it is not possible to change its 
firstValue property, even though firstValue is a variable 
property.

This behavior is due to structures being value types. When 
an instance of a value type is marked as a constant, so 
are all of its properties.
  • 如果一個結(jié)構(gòu)體實例被constant修飾蒜焊,它的所有屬性也是默認的常量

延遲存儲屬性(Lazy Stored Properties)

A lazy stored property is a property whose initial value 
is not calculated until the first time it is used. You 
indicate a lazy stored property by writing the lazy 
modifier before its declaration.
  • 延遲存儲屬性只有當(dāng)使用時才會被創(chuàng)建倒信,用lazy關(guān)鍵字修飾

例子:

class DataImporter{
    var filename = "data.txt"
}

class DataManager{
    lazy var importer = DataImporter()
    var data = [String]()
}

let manager = DataManager()
manager.data.append("Some data")
manager.data.append("Some more data")
print(manager.importer.filename)

執(zhí)行結(jié)果:

someVideoMode === otherVideoMode
someVideoMode !== thirdVideoMode
data.txt

計算屬性(Computed Properties)

In addition to stored properties, classes, structures, and 
enumerations can define computed properties, which do not 
actually store a value. Instead, they provide a getter and 
an optional setter to retrieve and set other properties 
and values indirectly.
  • 除了存儲屬性,類與結(jié)構(gòu)體泳梆,枚舉都可以定義計算屬性鳖悠,計算屬性是一個可選的setter來間接設(shè)置其他屬性或變量的值

例子:

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.center
square.center = Point(x: 15.0, y: 15.0)
print("square.origin is now at (\(square.origin.x), \(square.origin.y))")

執(zhí)行結(jié)果:

square.origin is now at (10.0, 10.0)

便捷的Setter聲明(Shorthand Setter Declaration)

If a computed property’s setter does not define a name for 
the new value to be set, a default name of newValue is 
used. Here’s an alternative version of the Rect structure, 
which takes advantage of this shorthand notation:
  • 如果一個計算屬性的的set方法沒有定義一個新的名字給這個新的值,那么默認的名字就是newValue

例子:

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{
            origin.x = newValue.x - (size.width / 2)
            origin.y = newValue.y - (size.height / 2)
        }
    }
}

只讀的計算屬性(Read-Only Computed Properties)

A computed property with a getter but no setter is known 
as a read-only computed property. A read-only computed 
property always returns a value, and can be accessed 
through dot syntax, but cannot be set to a different 
value.
  • 計算屬性如果只寫入了get方法沒有set方法优妙,那么就是只讀的計算屬性

例子:

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)")

例子:

the volume of fourByFiveByTwo is 40.0

屬性觀察器(Property Observers)

Property observers observe 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 property’s current value.

You can add property observers to any stored properties 
you define, except for lazy stored properties. You can 
also add property observers to any inherited property 
(whether stored or computed) by overriding the property 
within a subclass. You don’t need to define property 
observers for nonoverridden computed properties, because 
you can observe and respond to changes to their value in 
the computed property’s setter. Property overriding is 
described in Overriding.

You have the option to define either or both of these 
observers on a property:

- willSet is called just before the value is stored.
- didSet is called immediately after the new value is 
stored. 
  • 當(dāng)屬性發(fā)生變化時會觸發(fā)屬性觀察器乘综,可以給除了延遲存儲屬性的屬性添加觀察器。同樣子類繼承的屬性一樣也可以添加觀察器套硼,只需要子類中重載屬性即可卡辰。
  • willSet當(dāng)屬性將要變化是觸發(fā)
  • didSet當(dāng)屬性已經(jīng)發(fā)生變化時觸發(fā)

例子:

 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 = 10
stepCounter.totalSteps = 20

執(zhí)行結(jié)果:

About to set totalSteps to 10
Added 10 steps
About to set totalSteps to 20
Added 10 steps

全局變量與局部變量(Global and Local Variables)

Global variables are variables that are defined outside of 
any function, method, closure, or type context. Local 
variables are variables that are defined within a function, 
method, or closure context.
  • 全局變量是在函數(shù)、方法、閉包或任何類型之外定義的變量九妈,局部變量是在函數(shù)朴恳、方法或閉包內(nèi)部定義的變量。

例子:

var globalNum = 0;
func changeNumToTen(){
    var localNum = 10;
    globalNum = 10;
    print("globalNum:\(globalNum) localNum:\(localNum)");
}

changeNumToTen();
globalNum = 20;
print("globalNum:\(globalNum)");

執(zhí)行結(jié)果:

globalNum:10 localNum:10
globalNum:20

類型屬性(Type Properties)

Instance properties are properties that belong to an instance 
of a particular type. Every time you create a new instance of 
that type, it has its own set of property values, separate 
from any other instance.

You can also define properties that belong to the type 
itself, not to any one instance of that type. There will only 
ever be one copy of these properties, no matter how many 
instances of that type you create. These kinds of properties 
are called type properties.
  • 類型本身可以定義屬性允蚣,不管有多少個實例于颖,這些屬性只有唯一一份

類型屬性語法(Type Property Syntax)

You define type properties with the static keyword. For 
computed type properties for class types, you can use the 
class keyword instead to allow subclasses to override the 
superclass’s implementation. 
  • 使用關(guān)鍵字static來定義類型屬性,另外可以以使用關(guān)鍵字class來定義計算類型屬性嚷兔,讓子類可以重寫該方法(使用static的計算屬性不能被重寫)

例子:

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;
    }
}

class SubSomeClass:SomeClass{
    override class var overrideableComputedTypeProperty: Int {
        return 108;
    }
}

print(SomeStructure.storedTypeProperty)
SomeStructure.storedTypeProperty = "Another value."
print(SomeStructure.storedTypeProperty)
print(SomeEnumeration.computedTypeProperty)
print(SomeClass.computedTypeProperty)
print(SomeClass.overrideableComputedTypeProperty)
print(SubSomeClass.overrideableComputedTypeProperty)

執(zhí)行結(jié)果:

Some value.
Another value.
6
27
107
108
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末森渐,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子冒晰,更是在濱河造成了極大的恐慌同衣,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,858評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件壶运,死亡現(xiàn)場離奇詭異耐齐,居然都是意外死亡,警方通過查閱死者的電腦和手機蒋情,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評論 3 395
  • 文/潘曉璐 我一進店門埠况,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人棵癣,你說我怎么就攤上這事辕翰。” “怎么了狈谊?”我有些...
    開封第一講書人閱讀 165,282評論 0 356
  • 文/不壞的土叔 我叫張陵喜命,是天一觀的道長。 經(jīng)常有香客問我河劝,道長壁榕,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,842評論 1 295
  • 正文 為了忘掉前任赎瞎,我火速辦了婚禮牌里,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘煎娇。我一直安慰自己二庵,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,857評論 6 392
  • 文/花漫 我一把揭開白布缓呛。 她就那樣靜靜地躺著催享,像睡著了一般。 火紅的嫁衣襯著肌膚如雪哟绊。 梳的紋絲不亂的頭發(fā)上因妙,一...
    開封第一講書人閱讀 51,679評論 1 305
  • 那天,我揣著相機與錄音,去河邊找鬼攀涵。 笑死铣耘,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的以故。 我是一名探鬼主播蜗细,決...
    沈念sama閱讀 40,406評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼怒详!你這毒婦竟也來了炉媒?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,311評論 0 276
  • 序言:老撾萬榮一對情侶失蹤昆烁,失蹤者是張志新(化名)和其女友劉穎吊骤,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體静尼,經(jīng)...
    沈念sama閱讀 45,767評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡白粉,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了鼠渺。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片鸭巴。...
    茶點故事閱讀 40,090評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖系冗,靈堂內(nèi)的尸體忽然破棺而出奕扣,到底是詐尸還是另有隱情,我是刑警寧澤掌敬,帶...
    沈念sama閱讀 35,785評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站池磁,受9級特大地震影響奔害,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜地熄,卻給世界環(huán)境...
    茶點故事閱讀 41,420評論 3 331
  • 文/蒙蒙 一华临、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧端考,春花似錦雅潭、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至裂明,卻和暖如春椿浓,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評論 1 271
  • 我被黑心中介騙來泰國打工扳碍, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留提岔,地道東北人。 一個月前我還...
    沈念sama閱讀 48,298評論 3 372
  • 正文 我出身青樓笋敞,卻偏偏與公主長得像碱蒙,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子夯巷,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,033評論 2 355

推薦閱讀更多精彩內(nèi)容

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,822評論 6 342
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理赛惩,服務(wù)發(fā)現(xiàn),斷路器鞭莽,智...
    卡卡羅2017閱讀 134,659評論 18 139
  • Swift語法基礎(chǔ)(五)-- (類和結(jié)構(gòu)體、屬性喷面、方法) 本章將會介紹 類和結(jié)構(gòu)體對比結(jié)構(gòu)體和枚舉是值類型類是引用...
    寒橋閱讀 1,081評論 0 1
  • 我每天使用 Git 枉疼,但是很多命令記不住掐禁。一般來說,日常使用只要記住下圖6個命令,就可以了箩言。但是熟練使用,恐怕要記...
    Smallwolf_JS閱讀 347評論 0 2
  • 等你的日子緩慢悠長成福, 荷葉剛醒枚荣,晨光熹微。 我在等你边翁, 你 不知道翎承。 在街上徘徊, 想著此刻的你在哪符匾? 該走哪條路...
    慎何閱讀 329評論 6 3