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

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.

主站蜘蛛池模板: 乌拉特后旗| 蛟河市| 阜宁县| 西青区| 乾安县| 汕头市| 始兴县| 孟津县| 衡南县| 林州市| 凤阳县| 垣曲县| 赞皇县| 行唐县| 从江县| 平乐县| 寻甸| 屏东市| 个旧市| 石台县| 贺兰县| 金沙县| 周宁县| 军事| 隆回县| 尖扎县| 慈溪市| 宣化县| 宁城县| 洛宁县| 旬邑县| 灌阳县| 阿勒泰市| 东阿县| 双流县| 昭觉县| 宁武县| 界首市| 内乡县| 邛崃市| 临潭县|