import Foundation
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() ->String {
return "A shape with \(numberOfSides) sides."
}
}
// 注意这里的对象初始,需要传递name的属性数值进去
// 初始的时候一定要写上“name:“,否则编译器会认为没有进行初始化工作
var shape = NamedShape(name: "Bob")
// 下面是继承类的声明与使用
class Square: NamedShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
// 由于name属性是通过父类初始函数初始化的
// 所以必须调用父类的init方法初始化name属性
super.init(name: name)
// 可以直接使用父类属性
numberOfSides = 4
}
func area() -> Double {
return sideLength * sideLength
}
// 重载父类方法,一定要写明override,否则编译器会报错
override func simpleDescription() ->String {
return "A square with sides of length \(sideLength)."
}
}
let test = Square(sideLength: 5.2, name: "my test squre")
println(test.area())
println(test.simpleDescription())
以下是getter和setter的用法示例
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 quilateral triagle with side of length \(sideLength)"
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
println(triangle.perimeter)
triangle.perimeter = 9.9
println(triangle.sideLength)
以下是介绍类模块中willSet和didSet的用法,这部分比较特别
willSet可以在设置新的属性值之前运行,下面的示例是保证triangle和square的sideLength始终保持相等
class TriangleAndSquare {
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
}
var triangle: EquilateralTriangle {
willSet {
square.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")
println(triangleAndSquare.square.sideLength)
println(triangleAndSquare.triangle.sideLength)
// 如果是直接改变square中的sideLength的值,那么triangle中的sideLength是不会发生变化的
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
println(triangleAndSquare.triangle.sideLength)
类和结构体的主要区别是,结构体是值传递(依靠值的复制进行代码内部的传递),类是引用传递
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。