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

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.

主站蜘蛛池模板: 富阳市| 株洲市| 武穴市| 安平县| 密山市| 沾益县| 滨海县| 噶尔县| 玉环县| 冕宁县| 房山区| 开平市| 岳池县| 平乡县| 无极县| 莲花县| 武隆县| 高清| 浏阳市| 册亨县| 喀什市| 马鞍山市| 开远市| 普洱| 南和县| 高平市| 搜索| 隆德县| 阿克苏市| 汉寿县| 金乡县| 荣成市| 太和县| 固镇县| 新兴县| 连江县| 铁岭市| 静安区| 宁城县| 九寨沟县| 永州市|