structPoint{ var x =0.0, y =0.0 } structSize{ var width =0.0, height =0.0 } structRect{ var origin =Point() var size =Size() var center: Point { get { let centerX = origin.x + (size.width /2) let centerY = origin.y + (size.height /2) returnPoint(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 // initialSquareCenter is at (5.0, 5.0) print("square.origin is now at (\(square.origin.x), \(square.origin.y))") // Prints "square.origin is now at (10.0, 10.0)"
structCuboid{ var width =0.0, height =0.0, depth =0.0 var volume: Double { // 只读 Read-Only return width * height * depth } } let fourByFiveByTwo =Cuboid(width: 4.0, height: 5.0, depth: 2.0) print("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)") // Prints "the volume of fourByFiveByTwo is 40.0"
由上面的 省略 getter 中的 return 可知, 下面的写法依然正确
1 2 3 4 5 6 7 8 9
structCuboid{ var width =0.0, height =0.0, depth =0.0 var volume: Double { // 只读 Read-Only width * height * depth // 隐式return } } let fourByFiveByTwo =Cuboid(width: 4.0, height: 5.0, depth: 2.0) print("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)") // Prints "the volume of fourByFiveByTwo is 40.0"