感谢Github上The Swift Programming Language开源翻译的中文版,感谢极客学院wiki提供的PDF版本
SwiftTour是对Swift主要的语言特性有个速览,后续的教程会逐个展开阐述。
代码上传至Github,有兴趣的可以下载下来试试
// 使用class和类名创建一个类 class Shape { var numberOfSides = 0 func simpleDescription() ->String { return "A Shape with \(numberOfSides) sides" } } var shape = Shape() shape.numberOfSides = 7 var shapeDescription = shape.simpleDescription() // 使用init创建构造器,使用deinit创建一个析构函数 class NameShape { var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() ->String {
return "A Shape with \(numberOfSides) sides"
}
}
// 子类重写父类的方法需要用override标记
class Squre: NameShape {
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 = Squre(sideLength: 5.2,name: "My test Square")
test.area()
test.simpleDescription()
// 类的getter和setter
class EquilateralTriangle: NameShape {
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 triangel = EquilateralTriangle(sideLength: 3.1,name: "a triangle")
print(triangel.perimeter)
triangel.perimeter = 9.9
print(triangel.sideLength)
// 不需要计算属性,仍然需要在设置新值之前或之后运行代码,使用willset和didset
// 确保三角形的边长综合正方形的边长相同
class TriangleAndSquare { var triangle: EquilateralTriangle {
willSet {
square.sideLength = newValue.sideLength
}
}
var square: Squre {
willSet {
triangel.sideLength = newValue.sideLength
}
}
init(size: Double,name: String) {
square = Squre(sideLength: size,name: name)
triangle = EquilateralTriangle(sideLength: size,name: name)
}
}
var triangleAndSquare = TriangleAndSquare(size: 10,name: "Another tested Shape")
print(triangleAndSquare.square.sideLength)
print(triangleAndSquare.triangle.sideLength)
triangleAndSquare.triangle = EquilateralTriangle(sideLength: 30,name: "Other")
print(triangleAndSquare.triangle.sideLength)
print(triangleAndSquare.square.sideLength)
// 处理变量的可选值时,可以在操作前加?
let optionalSquare: Squre? = Squre(sideLength: 2.5,name: "Optional square")
let sideLength = optionalSquare?.sideLength
print(sideLength)