作為你程式代碼的構建基礎,類和結構體是一種多功能且靈活的構造體。通過使用與現存常量、變數、函數完全相同的語法來在類和結構體當中定義屬性和方法以添加功能。 ...
類和結構體
蘋果官方文檔 Classes and Structures
蘋果官方文檔翻譯 類和結構體
類與結構體的對比
定義語法
class SomeClass {
// class definition goes here
}
struct SomeStructure {
// structure definition goes here
}
一個實際的代碼例子如下:
struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced
}
類與結構體實例
let someResolution = Resolution()
let someVideoMode = VideoMode()
訪問屬性
print("The width of someResolution is \(someResolution.width)")
// prints "The width of someResolution is 0"
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)")
結構體類型的成員初始化器
let vga = Resolution(width: 640, height: 480)
但是,類實例不會接收預設的成員初始化器。
結構體和枚舉是值類型
值類型是一種當它被指定到常量或者變數,或者被傳遞給函數時會被拷貝的類型。
let hd = Resolution(width: 1920, height: 1080)
var cinema = hd
cinema.width = 2048
println("cinema is now \(cinema.width) pixels wide")
//println "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"
特征運算符
找出兩個常量或者變數是否引用自同一個類實例非常有用,為了允許這樣,Swift提供了兩個特點運算符:
相同於 ( ===)
不相同於( !==)
if tenEighty === alsoTenEighty {
print("tenEighty and alsoTenEighty refer to the same VideoMode instance.")
}
// prints "tenEighty and alsoTenEighty refer to the same VideoMode instance."
類和結構體之間的選擇
字元串,數組和字典的賦值與拷貝行為
詳見文檔原文