能夠經過使用常量、變量和函數徹底相同的語法來定義屬性和方法向類和結構添加功能。數據結構
Swift不須要爲自定義類和結構建立單獨的接口和實現文件,只須要在單個文件中定義一個類或結構體Swift會自動造成對其餘代碼可用的外部接口。ide
類和結構體的共同之處:函數
類具備的附加功能:指針
注意code
結構體是值類型,且沒有引用計數,類是引用類型。繼承
類和結構體定義語法相似,分別使用class和struct關鍵字。接口
class SomeClass { // class definition goes here } struct SomeStructure { // structure definition goes here }
注意內存
類和結構體的類型名採用首字母大寫的駝峯命名法,屬性和方法採用小寫的。ci
類和結構體的定義示例:rem
struct Resolution { var width = 0 var height = 0 } class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? }
類和結構體建立實例的語法也很是類似:
let someResolution = Resolution() let someVideoMode = VideoMode()
類和結構體建立實例都使用初始化器,初始化器的最簡單形式是使用類或結構體的類型名,後跟空括號。這樣會將全部屬性初始化爲默認值。
使用點語法訪問實例的屬性。
print("The width of someResolution is \(someResolution.width)") // Prints "The width of someResolution is 0"
Swift能夠直接設置結構屬性的子屬性:
print("The width of someVideoMode is \(someVideoMode.resolution.width)") // Prints "The width of someVideoMode is 0"
使用點語法給變量屬性設置新值:
someVideoMode.resolution.width = 1280 print("The width of someVideoMode is now \(someVideoMode.resolution.width)") // Prints "The width of someVideoMode is now 1280"
全部結構體會自動生成一個成員初始化器,經過名稱將實例的屬性的初始化值傳遞給成員初始化器:
let vga = Resolution(width: 640, height: 480)
而類結構不生成默認的成員初始化器。
值類型是將值分配給變量或常量或將其傳遞給函數時複製其值的類型,改變其中一個而不會影響另外一個。
Swift中的全部基本數據類型都是值類型,包括結構體和枚舉。
說明結構體是值類型的示例:
let hd = Resolution(width: 1920, height: 1080) var cinema = hd 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"
說明枚舉是值類型的示例:
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") } // Prints "The remembered direction is still .west"
當引用類型被分配給變量或常量或將其傳遞給函數時,不會複製引用類型,而是直接使用原實例的引用,這意味着修改其中一個值會直接反映到另外一個值。
let tenEighty = VideoMode() tenEighty.resolution = hd tenEighty.interlaced = true tenEighty.name = "1080i" tenEighty.frameRate = 25.0 let alsoTenEighty = tenEighty alsoTenEighty.frameRate = 30.0 print("The frameRate property of tenEighty is now \(tenEighty.frameRate)") // Prints "The frameRate property of tenEighty is now 30.0"
上述的類實例都分配給了常量,修改實例的屬性對常量自己的值無影響,只是改變內部的屬性,未修改其引用。
使用等於運算符判斷兩個常量或變量是否爲相同的類實例,即同一個引用,有兩個相等運算符:
`
if tenEighty === alsoTenEighty { print("tenEighty and alsoTenEighty refer to the same VideoMode instance.") } // Prints "tenEighty and alsoTenEighty refer to the same VideoMode instance."
C和Objective-C語言中使用指針來引用內存地址,而Swift中引用某個引用類型的實例與指針相似,但不是直接指向內存地址的指針,建立引用也不須要使用星號(*)。
使用類和結構體來定義複雜的自定義數據類型。
值類型和引用類型意味着結構體和類適合於不一樣類型的任務,依據如下原則考慮將一個數據類型定義爲一個結構體:
如下爲使用結構體的一些好的例子:
以上原則說明,封裝的屬性都是數值類型時一般選擇結構體。
在全部其餘條件下,定義爲一個類,並建立要經過引用進行管理和傳遞的類的實例。,這意味着大多數自定義數據結構應該是類而不是結構。