官术网_书友最值得收藏!

Classes

Let's start with an example of a simple class that represents a Point in an x, y coordinate system (Cartesian). Consider the following:

class Point {
var x: Double
var y: Double

init(x: Double, y: Double) {
self.x = x
self.y = y
}
}

Now, let's define a simple translate function that will mutate the x and y properties of the point objects by adding dx and dy to x and y, respectively:

func translate(point : Point, dx : Double, dy : Double) {
point.x += dx
point.y += dy
}

Now, we can create a point instance with, for example, an initial value of 0.0, and translate it to the position 1.0:

let point = Point(x: 0.0, y: 0.0)
translate(point: point, dx: 1.0, dy: 1.0)
point.x == 1.0
point.y == 1.0

Because classes follow reference semantics, only a reference to the point object is passed to the translate function; x and y are defined as var, and all of this code is valid.

主站蜘蛛池模板: 淮安市| 郴州市| 新田县| 伊川县| 孝昌县| 文登市| 株洲县| 苍山县| 沂源县| 从江县| 芦溪县| 郴州市| 象山县| 莱阳市| 兖州市| 郑州市| 西平县| 阿合奇县| 大安市| 白朗县| 巩留县| 万源市| 连城县| 六盘水市| 同德县| 图木舒克市| 乳源| 米易县| 麻城市| 景泰县| 黄浦区| 贵阳市| 偏关县| 南漳县| 永宁县| 常熟市| 大余县| 普安县| 尼木县| 邛崃市| 丹寨县|