1、使用关键字class
来创建一个类。
class AnimateDog{
var dogEate = 1
func footDes() -> String {
return "小狗要吃\(dogEate)盆食物!"
}
}
2、使用类名 + ()创建类的实例。
var smallDog = AnimateDog()
smallDog.dogEate = 2
var dogFoot = smallDog.footDes()
3、类在初始化的时候必须自己声明初始化构造器:
指定构造器(Designated Initializers)
指定构造器:对所有没有默认值的非可选属性进行初始化。
class AnimateName {
var dogEate:Int = 0
var name: String
init(name: String) {
self.name = name
}
func footDes() -> String {
return "小狗要吃\(dogEate)盆食物!"
}
}
`#初始化调用:`
let test = AnimateName (name: "你好")
deinit如果需要在取消分配对象之前执行一些清理,请使用创建取消初始化程序。
4、除了存储的简单属性之外,属性还可以包含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 equilateral triangle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
分析:EquilateralTriangle该类的初始化程序有三个不同的步骤:
1.设置子类声明的属性的值。
2.调用超类的初始化程序。
3.更改超类定义的属性值。此时也可以使用方法,getter或setter进行任何其他设置工作。
5、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")
网友评论