點擊查看源碼git
struct Resolution { var width = 0 var height = 0 } class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? } ///類和結構體 class ClassesStructures: NSObject { func test() { // self.testClassStruct() // 類和結構體 // self.testStructuresAndEnumerationsAreValueTypes() // 結構體和枚舉是值類型 // self.testClassesAreReferenceTypes() // 類是引用類型 // self.testIdentityOperators() // 恆等算子 } //類和結構體測試 func testClassStruct() { //初始化 let someResolution = Resolution() let someVideoMode = VideoMode() //訪問屬性 print("someResolution.width:\(someResolution.width)") print("someVideoMode.resolution.width:\(someVideoMode.resolution.width)") someVideoMode.resolution.width = 1280 print("someVideoMode.resolution.width:\(someVideoMode.resolution.width)") //經過成員初始化結構體 let vga = Resolution(width: 640, height: 480) print(vga) /* print someResolution.width:0 someVideoMode.resolution.width:0 someVideoMode.resolution.width:1280 Resolution(width: 640, height: 480) */ } //結構體和枚舉是值類型 func testStructuresAndEnumerationsAreValueTypes() { //結構體測試 let hd = Resolution(width: 1920, height: 1080) var cinema = hd cinema.width = 2048 //改變cinema的值 不會改變hd中的值 print("cinema.width:\(cinema.width)") print("hd.width:\(hd.width)") //枚舉測試 enum CompassPoint { case north, south, east, west } var currentDirection = CompassPoint.west let rememberedDirection = currentDirection //改變currentDirection rememberedDirection的值不會變化 currentDirection = .east print("\(rememberedDirection)") /* print cinema.width:2048 hd.width:1920 west */ } //類是引用類型 func testClassesAreReferenceTypes() { let tenEighty = VideoMode() tenEighty.frameRate = 25.0 // 引用tenEighty到alsoTenEighty 並改變alsoTenEighty中的值 let alsoTenEighty = tenEighty alsoTenEighty.frameRate = 30.0 print("tenEighty.frameRate:\(tenEighty.frameRate)") /* print tenEighty.frameRate:30.0 */ } //恆等算子 func testIdentityOperators() { //恆等算子是===或!== let tenEighty = VideoMode() let alsoTenEighty = tenEighty if tenEighty === alsoTenEighty { print("相同實例") } /* print 相同實例 */ } }