1.类(class)
使用关键字 class 创建一个类。属性直接在类里面声明,属性可以是变量,也可以是常量。方法和函数的创建方法一致。
class Shape { var numberOfSides = 0 func simpleDescription() -> String { return "A shape with (numberOfSides) sides." } }
2.对象(object)
对象的创建很容易。在类名后面加一个圆括号就可以创建类的实例。使用 “.” 访问实例的属性和方法。
var shape = Shape() shape.numberOfSides = 7 var shapeDescription = shape.simpleDescription()
上面的类 Shape 比较简单。下面的Shape在初始化的时候对属性进行设置,使用到了初始化方法 init。
class NamedShape { var numberOfSides: Int = 0 var name: String init(name: String) { self.name = name } func simpleDescription() -> String { return "A shape with (numberOfSides) sides." } }
注意,在 init 方法里面,使用 self 区分成员变量 name 和 参数 name。
有默认初始化方法 init, 就有默认销毁方法 deinit,如果对象在销毁时有需要清理,可以实现deinit 方法做清理操作。
3.子类(subclass)
在类名后面加上父类名字,用冒号区分,这个类就是子类。
子类可以使用关键字 override 覆盖父类的方法。如果子类实现父类的方法而没有添加关键字override,编译器会视为错误。
class Square: NamedShape { var sideLength: Double init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func area() -> Double { return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length (sideLength)." } } let test = Square(sideLength: 5.2, name: "my test square") test.area() test.simpleDescription()
可以给类中的属性添加 get 和 set 方法。
class EquilateralTriangle: NamedShape { var sideLength: Double = 0.0 init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 3 } var perimeter: Double { get { return 3.0 * sideLength } set { sideLength = newValue / 3.0 } } override func simpleDescription() -> String { return "An equilateral triangle with sides of length (sideLength)." } } var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle") print(triangle.perimeter) triangle.perimeter = 9.9 print(triangle.sideLength)
值得注意,在 初始化方法里面做了三步。
- 对子类属性赋值
- 调用父类初始化方法
- 修改父类的属性值
如果想在给属性值赋值之前或者之后做一些操作,可以使用 关键字 willSet 和 didSet。
class TriangleAndSquare { var triangle: EquilateralTriangle { willSet { square.sideLength = newValue.sideLength } } var square: Square { willSet { triangle.sideLength = newValue.sideLength } } init(size: Double, name: String) { square = Square(sideLength: size, name: name) triangle = EquilateralTriangle(sideLength: size, name: name) } } var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape") print(triangleAndSquare.square.sideLength) print(triangleAndSquare.triangle.sideLength) triangleAndSquare.square = Square(sideLength: 50, name: "larger square") print(triangleAndSquare.triangle.sideLength)
类的实例也可以作为可选值。
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare?.sideLength
恩,努力!