Swift的类,及存储属性,计算发发样码
进入机械的学习模式, 就是把代友敲完。 以期能加深些记忆。 struct Resolution { var width = 0 var height = 0 } class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? } let someResolution = Resolution(width: 640, height: 480) let someVideoMode = VideoMode() print("The width of someResolution is \(someResolution.width)") someVideoMode.resolution.width = 1280 print("The width of someVedioMode is \(someVideoMode.resolution.width)") let hd = Resolution(width: 1920, height: 1080) var cinema = hd cinema.width = 2048 print("cienma is now \(cinema.width) pixels wide") print("hd is still \(hd.width) pixels width") 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") } 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)") struct Point { var x = 0.0, y = 0.0 } struct Size { var width = 0.0, height = 0.0 } struct Rect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set(newCenter) { origin.x = newCenter.x - (size.width / 2) origin.y = newCenter.y - (size.height / 2) } } } var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0)) let initialSquareCenter = square.center square.center = Point(x: 15.0, y: 15.0) print("square.origin is now at (\(square.origin.x), \(square.origin.y))") class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps) { print("About to set totalSteps to \(newTotalSteps)") } didSet { if totalSteps > oldValue { print("Added \(totalSteps - oldValue) steps") } } } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 stepCounter.totalSteps = 360 stepCounter.totalSteps = 896 struct SomeStructure { static var storedTypeProperty = "Some value" static var computedTypeProperty: Int { return 1 } } enum SomeEnumeration { static var storedTypeProperty = "Some value" static var computedTypeProperty: Int { return 6 } } class SomeClass { static var storedTypeProperty = "Some value" static var computedTypeProperty: Int { return 27 } class var overrideableComputedTypeProperty: Int { return 107 } } print(SomeStructure.storedTypeProperty) SomeStructure.storedTypeProperty = "Another value" print(SomeStructure.storedTypeProperty) print(SomeEnumeration.computedTypeProperty) print(SomeClass.computedTypeProperty)