1.來(lái)看看官方說(shuō)明類和結(jié)構(gòu)體的相同和不同:
Classes and structures in Swift have many things in common. Both can:(相同點(diǎn))
- Define properties to store values(定義屬性來(lái)存儲(chǔ)值)
- Define methods to provide functionality(定義提供功能的方法)
- Define subscripts to provide access to their values using subscript syntax (定義下標(biāo)以使用下標(biāo)語(yǔ)法提供對(duì)其值的訪問(wèn))
- Define initializers to set up their initial state (定義初始化器來(lái)設(shè)置它們的初始狀態(tài))
- Be extended to expand their functionality beyond a default implementation (擴(kuò)展到超出默認(rèn)實(shí)現(xiàn)的功能)
- Conform to protocols to provide standard functionality of a certain kind (符合協(xié)議提供某種標(biāo)準(zhǔn)功能)
Classes have additional capabilities that structures do not:(類具有的結(jié)構(gòu)體沒(méi)有的特點(diǎn))
- Inheritance enables one class to inherit the characteristics of another.(繼承使一個(gè)類能夠繼承另一個(gè)類的特性牲蜀。)
- Type casting enables you to check and interpret the type of a class instance at runtime.(類型轉(zhuǎn)換使您能夠在運(yùn)行時(shí)檢查和解釋類實(shí)例的類型蚂子。)
- Deinitializers enable an instance of a class to free up any resources it has assigned.(取消初始化程序使類的一個(gè)實(shí)例釋放它分配的任何資源窍育。)
- Reference counting allows more than one reference to a class instance.(引用計(jì)數(shù)允許多個(gè)對(duì)類實(shí)例的引用截亦。)
注意:
結(jié)構(gòu)在代碼中傳遞時(shí)總是被復(fù)制,而不使用引用計(jì)數(shù)晶姊。
2.類是引用類型扒接,結(jié)構(gòu)體是值類型
聲明一個(gè)結(jié)構(gòu)體和類
struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
- 初始化,結(jié)構(gòu)體會(huì)自動(dòng)生成2種初始化方法
let someResolution = Resolution()
let someResolution2 = Resolution(width: 29, height: 19)
let somVideoMode = VideoMode()
- 值類型
所有結(jié)構(gòu)和枚舉都是Swift中的值類型。這意味著您創(chuàng)建的任何結(jié)構(gòu)和枚舉實(shí)例(以及它們作為屬性的任何值類型)在您的代碼中傳遞時(shí)總是被復(fù)制们衙。
如:先生成一個(gè)結(jié)構(gòu)體钾怔,在賦值另一個(gè)
let hd = Resolution(width: 1920, height: 1080)
var cinema = hd
改變cinema
的width
,而hd
的width
不變,當(dāng)cinema給定當(dāng)前值時(shí)hd,存儲(chǔ)在其中的值hd被復(fù)制到新cinema實(shí)例中砍艾。最終結(jié)果是兩個(gè)完全分離的實(shí)例蒂教,它們恰好包含相同的數(shù)值.這情況適合所有的值類型,枚舉脆荷,字典凝垛,數(shù)組懊悯。。梦皮。
cinema.width = 2048
print("cinema is now \(cinema.width) pixels wide")
// Prints "cinema is now 2048 pixels wide"
print("hd is still \(hd.width) pixels wide")
// Prints "hd is still 1920 pixels wide"
- 引用類型
聲明一個(gè)VideoMode
類
let tenEighty = VideoMode()
tenEighty.resolution = hd
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0
接下來(lái)炭分,tenEighty
被分配一個(gè)新的常量,調(diào)用alsoTenEighty
剑肯,并alsoTenEighty
修改frameRate
:
let alsoTenEighty = tenEighty
alsoTenEighty.frameRate = 30.0
tenEighty的frameRate屬性仍為30.0捧毛,這既是引用類型
print("The frameRate property of tenEighty is now \(tenEighty.frameRate)")
// Prints "The frameRate property of tenEighty is now 30.0"