Structures and Classes 程式範例 — Apple’s The Swift Programming Language
Sep 8, 2018 · 5 min read
Definition Syntax
定義 struct 和 class 型別。
例子: 定義 struct Resolution & class VideoMode。
struct Resolution { var width = 0 var height = 0}class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String?}
Structure and Class Instances
建立 struct & class 型別的東西。
例子: 建立 Resolution & VideoMode 型別的東西。
let someResolution = Resolution()let someVideoMode = VideoMode()
Accessing Properties
利用 . 存取 property。
print("The width of someResolution is \(someResolution.width)")print("The width of someVideoMode is \(someVideoMode.resolution.width)")someVideoMode.resolution.width = 1280print("The width of someVideoMode is now \(someVideoMode.resolution.width)")
Memberwise Initializers for Structure Types
struct 有 Memberwise Initializer,生成 struct 型別的東西時,可以傳入每個 property 的內容。
let vga = Resolution(width: 640, height: 480)Structures and Enumerations Are Value Types
struct 是 value type。
= (assigned) 或當參數傳入 function 時,會複製一個一樣內容的東西。
cinema & hd 是不同的東西(two instances)。
let hd = Resolution(width: 1920, height: 1080)var cinema = hdcinema.width = 2048print("cinema is now \(cinema.width) pixels wide")print("hd is still \(hd.width) pixels wide")
enum 是 value type。
enum CompassPoint { case north, south, east, west mutating func turnNorth() { self = .north }}var currentDirection = CompassPoint.westlet rememberedDirection = currentDirectioncurrentDirection.turnNorth()print("The current direction is \(currentDirection)")print("The remembered direction is \(rememberedDirection)")
Classes Are Reference Types
class 是 reference type。
= (assigned) 或當參數傳入 function 時,指到同一個東西。
tenEighty & alsoTenEighty 是同一個東西。
let tenEighty = VideoMode()tenEighty.resolution = hdtenEighty.interlaced = truetenEighty.name = "1080i"tenEighty.frameRate = 25.0let alsoTenEighty = tenEightyalsoTenEighty.frameRate = 30.0print("The frameRate property of tenEighty is now \(tenEighty.frameRate)")
Identity Operators
用 === 判斷是否指到同一個東西。
if tenEighty === alsoTenEighty { print("tenEighty and alsoTenEighty refer to the same VideoMode instance.")}
