分別定義結(jié)構(gòu)體和類
struct Resolution{ // 結(jié)構(gòu)體
? ? ? var width=0
? ? ? var height=0
}
class VideoMode{ // 類 包含結(jié)構(gòu)體惠豺,做為屬性
? ? ?var resolution=Resolution()
? ? ?var interlaced=false
? ? ?var frameRate=0.0
? ? ?var name:String?
}
實(shí)例化結(jié)構(gòu)體和類
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? // 與Objective-C不同,Swift允許您直接設(shè)置結(jié)構(gòu)屬性的子屬性。
print("The width of someVideoMode is now\(someVideoMode.resolution.width)") ? ?// Prints "The width of someVideoMode is now 1280"
結(jié)構(gòu)體成員變量初始化
let vga=Resolution(width:640,height:480) ?
與結(jié)構(gòu)不同戒财,類實(shí)例不接收默認(rèn)的成員初始化。
Classes Are Reference Types // 類是引用類型? 指針指向同一個(gè)地址孝扛,改變的是同一個(gè)對(duì)象
Structures and Enumerations Are Value Types ?//結(jié)構(gòu)體和枚舉是值類型 ,值類型是一種類型苦始,當(dāng)其被分配給變量或常量時(shí),或者當(dāng)它被傳遞給函數(shù)時(shí)理郑,它的值被復(fù)制咨油。
let hd=Resolution(width:1920,height:1080)
var cinema=hd ? // copy
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"
Identity Operators // 身份操作符 ?判斷兩個(gè)常量或變量是否指向一個(gè)類的完全相同的實(shí)例。
=== ? // 是 ? ? ? !== ? ?//不是 ? ? ? ? ?== ?// 相等役电,值的相等 ? ? ?!= ?// 不相等,值的不相等
在Swift中冀膝,許多基本數(shù)據(jù)類型(如String霎挟,Array和Dictionary)被實(shí)現(xiàn)為結(jié)構(gòu)體,也就是說他們賦值的時(shí)候都是copy , ?This behavior is different from Foundation:NSString,NSArray, andNSDictionaryare implemented as classes, not structures. 在OC中不一樣了氓扛。