From 201147d72c38a2b2d57fc4f626c2f08c3daef354 Mon Sep 17 00:00:00 2001 From: Shiny Zhu Date: Sun, 8 Jun 2014 07:57:02 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E2=80=9C=E8=AE=A1=E7=AE=97?= =?UTF-8?q?=E5=B1=9E=E6=80=A7=E2=80=9D=E5=86=85=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- source/chapter2/10_Properties.md | 33 ++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/source/chapter2/10_Properties.md b/source/chapter2/10_Properties.md index d710c18e..5efe58c0 100644 --- a/source/chapter2/10_Properties.md +++ b/source/chapter2/10_Properties.md @@ -105,3 +105,36 @@ Swift编程语言中把这些理论统一用属性来实现。Swift中的属性 ## 计算属性 +除存储属性外,类、结构体和枚举可以定义*计算属性*,计算属性不直接存储值,而是提供一个getter来获取值,一个可选的setter来间接设置值。 + +``` +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) +println("square.origin is now at (\(square.origin.x), \(square.origin.y))") +// prints "square.origin is now at (10.0, 10.0)” + +``` +