Swift4 基礎(chǔ)部分: Classes and Structures

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

系列文章:

比較類與結(jié)構(gòu)體(Comparing Classes and Structures)

Classes and structures in Swift have many things in common. Both can:

- Define properties to store values
- Define methods to provide functionality
- Define subscripts to provide access to their values using subscript syntax
- Define initializers to set up their initial state
- Be extended to expand their functionality beyond a default implementation
- Conform to protocols to provide standard functionality of a certain kind
- 
For more information, see Properties, Methods, Subscripts, Initialization, Extensions, and Protocols.

Classes have additional capabilities that structures do not:

- Inheritance enables one class to inherit the characteristics of another.
- Type casting enables you to check and interpret the type of a class instance at runtime.
- Deinitializers enable an instance of a class to free up any resources it has assigned.
- Reference counting allows more than one reference to a class instances

Swift 中類和結(jié)構(gòu)體有很多共同點(diǎn)兼雄。共同處在于:

  • 定義屬性用于存儲(chǔ)值
  • 定義方法用于提供功能
  • 定義附屬腳本用于訪問值
  • 定義構(gòu)造器用于生成初始化值
  • 通過擴(kuò)展以增加默認(rèn)實(shí)現(xiàn)的功能
  • 符合協(xié)議以對(duì)某類提供標(biāo)準(zhǔn)功能

與結(jié)構(gòu)體相比,類還有如下的附加功能:

  • 繼承允許一個(gè)類繼承另一個(gè)類的特征
  • 類型轉(zhuǎn)換允許在運(yùn)行時(shí)檢查和解釋一個(gè)類實(shí)例的類型
  • 解構(gòu)器允許一個(gè)類實(shí)例釋放任何其所被分配的資源
  • 引用計(jì)數(shù)允許對(duì)一個(gè)類的多次引用

定義語法(Definition Syntax)

Classes and structures have a similar definition syntax. 
You introduce classes with the class keyword and 
structures with the struct keyword. 

例子:

struct Resolution {
    var width = 0
    var height = 0
}

class VideoMode {
    var resolution = Resolution()
    var interlaced = false
    var frameRate = 0.0
    var name: String?
}

var someResolution = Resolution();
someResolution.width = 10;
someResolution.height = 10;
var someVideoMode = VideoMode();
someVideoMode.resolution = someResolution;
someVideoMode.frameRate = 1.0;
someVideoMode.name = "mp4";

print("someVideoMode.resolution: (\(someVideoMode.resolution.width) \(someVideoMode.resolution.height)),someVideoMode.name \(someVideoMode.name)");

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

someVideoMode.resolution: (10 10),someVideoMode.name Optional("mp4")

結(jié)構(gòu)體與枚舉都是值類型數(shù)據(jù)(Structures and Enumerations Are Value Types)

A value type is a type whose value is copied when it is 
assigned to a variable or constant, or when it is passed 
to a function.

結(jié)構(gòu)體例子:

struct Resolution {
    var width = 0
    var height = 0
}

let hd = Resolution(width:1920,height:1080)
var cinema = hd
cinema.width = 2048
print("cinema is now \(cinema.width) pixels wide")
print("hd is still \(hd.width) pixels wide")

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

cinema is now 2048 pixels wide
hd is still 1920 pixels wide

枚舉例子:

enum CompassPoint {
    case north, south, east, west
}
var currentDirection = CompassPoint.west
let rememberedDirection = currentDirection
currentDirection = .east
if rememberedDirection == .west {
    print("The remembered direction is still .west")
}

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

The remembered direction is still .west

類是引用類型數(shù)據(jù)(Classes Are Reference Types)

Unlike value types, reference types are not copied when 
they are assigned to a variable or constant, or when they 
are passed to a function. Rather than a copy, a reference 
to the same existing instance is used instead.

例子:

struct Resolution {
    var width = 0
    var height = 0
}

class VideoMode {
    var resolution = Resolution()
    var interlaced = false
    var frameRate = 0.0
    var name: String?
}

var someVideoMode = VideoMode();
someVideoMode.name = "mp4";

var otherVideoMode = someVideoMode;
otherVideoMode.name = "AVI"
print("someVideoMode.name : (\(someVideoMode.name)");

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

someVideoMode.name : (Optional("AVI")

恒等式操作符(Identity Operators)

It can sometimes be useful to find out if two constants or 
variables refer to exactly the same instance of a class. 
To enable this, Swift provides two identity operators:

Identical to (===)

Not identical to (!==)

接著上述的例子:

struct Resolution {
    var width = 0
    var height = 0
}

class VideoMode {
    var resolution = Resolution()
    var interlaced = false
    var frameRate = 0.0
    var name: String?
}

var someVideoMode = VideoMode();
someVideoMode.name = "mp4";

var otherVideoMode = someVideoMode;
otherVideoMode.name = "AVI"

var thirdVideoMode = VideoMode();

if someVideoMode === otherVideoMode{
    print("someVideoMode === otherVideoMode")
}

if someVideoMode !== thirdVideoMode{
    print("someVideoMode !== thirdVideoMode")
}

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

someVideoMode === otherVideoMode
someVideoMode !== thirdVideoMode

類和結(jié)構(gòu)體的選擇(Choosing Between Classes and Structures)

You can use both classes and structures to define custom data types to use as the building blocks of your program’s 
code.

However, structure instances are always passed by value, 
and class instances are always passed by reference. This 
means that they are suited to different kinds of tasks. As you consider the data constructs and functionality that 
you need for a project, decide whether each data construct 
should be defined as a class or as a structure.

As a general guideline, consider creating a structure when 
one or more of these conditions apply:

- The structure’s primary purpose is to encapsulate a few 
relatively simple data values.

- It is reasonable to expect that the encapsulated values 
will be copied rather than referenced when you assign or 
pass around an instance of that structure.

- Any properties stored by the structure are themselves 
value types, which would also be expected to be copied rather than referenced.

- The structure does not need to inherit properties or behavior from another existing type.

Examples of good candidates for structures include:

- The size of a geometric shape, perhaps encapsulating a width property and a height property, both of type Double.

- A way to refer to ranges within a series, perhaps encapsulating a start property and a length property, both of type Int.

- A point in a 3D coordinate system, perhaps encapsulating x, y and z properties, each of type Double.


In all other cases, define a class, and create instances 
of that class to be managed and passed by reference. In 
practice, this means that most custom data constructs 
should be classes, not structures.

按照通用的準(zhǔn)則帽蝶,當(dāng)符合一條或多條以下條件時(shí)赦肋,請(qǐng)考慮構(gòu)建結(jié)構(gòu)體:

  • 結(jié)構(gòu)體的主要目的是用來封裝少量相關(guān)簡單數(shù)據(jù)值。
  • 有理由預(yù)計(jì)一個(gè)結(jié)構(gòu)體實(shí)例在賦值或傳遞時(shí),封裝的數(shù)據(jù)將會(huì)被拷貝而不是被引用金砍。
  • 任何在結(jié)構(gòu)體中儲(chǔ)存的值類型屬性局蚀,也將會(huì)被拷貝,而不是被引用恕稠。
  • 結(jié)構(gòu)體不需要去繼承另一個(gè)已存在類型的屬性或者行為。

合適的結(jié)構(gòu)體候選者包括:

  • 幾何形狀的大小扶欣,封裝一個(gè)width屬性和height屬性鹅巍,兩者均為Double類型。
  • 一定范圍內(nèi)的路徑料祠,封裝一個(gè)start屬性和length屬性骆捧,兩者均為Int類型。
  • 三維坐標(biāo)系內(nèi)一點(diǎn)髓绽,封裝x敛苇,y和z屬性,三者均為Double類型顺呕。

字符串與集合類型的賦值和拷貝行為(Assignment and Copy Behavior for Strings, Arrays,and Dictionaries)

In Swift, many basic data types such as String, Array, and 
Dictionary are implemented as structures. This means that 
data such as strings, arrays, and dictionaries are copied 
when they are assigned to a new constant or variable, or 
when they are passed to a function or method.
  • 在Swift中String,Array,Dictionary都是以結(jié)構(gòu)體的方式實(shí)現(xiàn)的枫攀。因此當(dāng)使用它們賦值或者傳入函數(shù)作為參數(shù)時(shí)都是以拷貝的方式傳入。

例子:

var array:[Int] = [1,2,3]
var otherArray = array
otherArray.append(4)
print("array:\(array),otherArray:\(otherArray)")

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

array:[1, 2, 3],otherArray:[1, 2, 3, 4]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末株茶,一起剝皮案震驚了整個(gè)濱河市来涨,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌启盛,老刑警劉巖蹦掐,帶你破解...
    沈念sama閱讀 216,496評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異僵闯,居然都是意外死亡卧抗,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門鳖粟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來社裆,“玉大人,你說我怎么就攤上這事牺弹∑致恚” “怎么了?”我有些...
    開封第一講書人閱讀 162,632評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵张漂,是天一觀的道長晶默。 經(jīng)常有香客問我,道長航攒,這世上最難降的妖魔是什么磺陡? 我笑而不...
    開封第一講書人閱讀 58,180評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上币他,老公的妹妹穿的比我還像新娘坞靶。我一直安慰自己,他們只是感情好蝴悉,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,198評(píng)論 6 388
  • 文/花漫 我一把揭開白布彰阴。 她就那樣靜靜地躺著,像睡著了一般拍冠。 火紅的嫁衣襯著肌膚如雪尿这。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,165評(píng)論 1 299
  • 那天庆杜,我揣著相機(jī)與錄音射众,去河邊找鬼。 笑死晃财,一個(gè)胖子當(dāng)著我的面吹牛叨橱,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播断盛,決...
    沈念sama閱讀 40,052評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼罗洗,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼!你這毒婦竟也來了郑临?” 一聲冷哼從身側(cè)響起栖博,我...
    開封第一講書人閱讀 38,910評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎厢洞,沒想到半個(gè)月后仇让,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,324評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡躺翻,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,542評(píng)論 2 332
  • 正文 我和宋清朗相戀三年丧叽,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片公你。...
    茶點(diǎn)故事閱讀 39,711評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡踊淳,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出陕靠,到底是詐尸還是另有隱情迂尝,我是刑警寧澤,帶...
    沈念sama閱讀 35,424評(píng)論 5 343
  • 正文 年R本政府宣布剪芥,位于F島的核電站垄开,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏税肪。R本人自食惡果不足惜溉躲,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,017評(píng)論 3 326
  • 文/蒙蒙 一榜田、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧锻梳,春花似錦箭券、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至荆永,卻和暖如春庆捺,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背屁魏。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評(píng)論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留捉腥,地道東北人氓拼。 一個(gè)月前我還...
    沈念sama閱讀 47,722評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像抵碟,于是被迫代替她去往敵國和親桃漾。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,611評(píng)論 2 353

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

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫拟逮、插件撬统、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,094評(píng)論 4 62
  • 常量與變量使用let來聲明常量,使用var來聲明變量敦迄。聲明的同時(shí)賦值的話恋追,編譯器會(huì)自動(dòng)推斷類型。值永遠(yuǎn)不會(huì)被隱式轉(zhuǎn)...
    莫_名閱讀 448評(píng)論 0 1
  • 簡單搭建監(jiān)控系統(tǒng) 基礎(chǔ)環(huán)境: 安裝k2-compose 下載監(jiān)控系統(tǒng)部署模版另存為k2-compose.yml,或...
    rm_rf閱讀 790評(píng)論 0 1
  • I:在表達(dá)稱贊時(shí),如果能先描述所稱贊的具體內(nèi)容脾猛,并且加上對(duì)方的稱謂或類似獨(dú)有信息的話撕彤,能讓對(duì)方感到獲得了特別的關(guān)注...
    幸福虛度的野人閱讀 247評(píng)論 0 2
  • 12月29日-12月30日 下面這段話是一位圈柚在圈圈三問中的提問,請(qǐng)你幫她梳理思路猛拴,概括出ta所表達(dá)的主題羹铅,來更...
    孫悟飯Y閱讀 244評(píng)論 0 1