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

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.

主站蜘蛛池模板: 济宁市| 娱乐| 金山区| 卫辉市| 手游| 都兰县| 甘肃省| 西乌| 乌海市| 永德县| 开平市| 荆州市| 天水市| 永顺县| 固阳县| 皮山县| 宁阳县| 疏附县| 搜索| 罗山县| 荔波县| 呼伦贝尔市| 石楼县| 周宁县| 波密县| 怀仁县| 邵东县| 甘洛县| 白沙| 涡阳县| 平阴县| 南岸区| 且末县| 武城县| 沅陵县| 中山市| 石门县| 彭泽县| 苏尼特左旗| 东阳市| 淮安市|