1. 程式人生 > >swift類和結構體(一)

swift類和結構體(一)

An instance of a class is traditionally known as an object. However, Swift classes and structures are much closer in functionality than in other languages, and much of this chapter describes functionality that can apply to instances of either a class or a structure type. Because of this, the more general term instance is used.
通常一個類的例項被稱為物件。然而,swift中類和結構體比其他任何一門語言都要接近。本章節描述的許多功能都可以應用在類和結構體上。因此,大多數屬於上我們應用例項。
結構體和類的異同


相同點:
1.定義屬性用於儲存值。
2.定義函式以提供功能
3.定義下標,以便用下標語法來訪問它們的值。
4.定義初始化程式,以建立它們的廚師狀態。
5.通過擴充套件來擴充套件它們的預設實現。
6.利用協議來完成特定標準功能。
和結構體相比,類還有結構體不具有的附加功能:
1.繼承使類一個類繼承另一個類的特性。
2.型別轉換允許你在執行時,檢查和解釋一個類例項的型別。
3.取消初始化器,允許一類的例項釋放它所佔有的資源。
4.計數器允許對一個例項進行多次引用。
這裡寫圖片描述
注意
結構體在您的程式碼中傳遞的時候不是進行的引用,而總是被拷貝。
定義
這裡寫圖片描述
注意
這裡寫圖片描述
定義類和結構體的命名,都要用首字母為大寫的駝峰命名法。相反,命名屬性和方法要要用矮駝峰來和型別進行區分。
類和結構體的例項

這裡寫圖片描述
類和結構體的例項比較簡單,只需要在類名後邊加上一對括號即可。例項的屬性值就是預設值,例項的更多初始化細節在Initialization方法裡邊。
屬性訪問
swift的屬性比較簡單,直接設定即可。
結構體型別的初始化器
All structures have an automatically-generated memberwise initializer, which you can use to initialize the member properties of new structure instances. Initial values for the properties of the new instance can be passed to the memberwise initializer by name:
所有的結構體都有一個自動生成的初始化器,它可以用來初始化新結構體的屬性。為例項的初始化值,可以通過名字傳遞到初始化器中。
這裡寫圖片描述

Unlike structures, class instances do not receive a default memberwise initializer. Initializers are described in more detail in Initialization.
不像結構體,類沒有這種預設的初始化器。