Structures and Classes 程式範例 — Apple’s The Swift Programming Language

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.")}

彼得潘的 Swift iOS App 開發問題解答集

彼得潘和學生們在開發 iOS App 路上曾經解決的問題集

彼得潘的 iOS App Neverland

Written by

彼得潘的 Swift 程式設計入門,App程式設計入門作者,彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,http://apppeterpan.strikingly.com

彼得潘的 Swift iOS App 開發問題解答集

彼得潘和學生們在開發 iOS App 路上曾經解決的問題集

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade