Swift 将为所有属性已提供默认值的且自身没有定义任何构造器的结构体或基类,提供一个默认的构造器。这个默认构造器将简单的创建一个所有属性值都设置为默认值的实例。
class Rectangle {
var width : Double
var height : Double
init(width : Double, height : Double) { ①
self.width = width
self.height = height
}
init(W width : Double,H height : Double) { ②
self.width = width
self.height = height
}
init(length : Double) { ③
self.width = length
self.height = length
}
init() { ④
self.width = 640.0
self.height = 940.0
}
}
var rectc1 = Rectangle(width : 320.0, height : 480.0) ⑤
println("长方形:(rectc1.width) x (rectc1.height)")
var rectc2 = Rectangle(W : 320.0, H : 480.0) ⑥
println("长方形:(rectc2.width) x (rectc2.height)")
var rectc3 = Rectangle(length: 500.0) ⑦
println("长方形3:(rectc3.width) x (rectc3.height)")
var rectc4 = Rectangle() ⑧
与函数一样,方法也存在重载,其重载的方式与函数一致。那么作为构造器的特殊方法,是否也存在重载呢?答案是肯定的。
一、构造器重载概念
Swift中函数重载的条件也适用于构造器,条件如下:
函数有相同的名字;
参数列表不同或返回值类型不同,或外部参数名不同;
Swift中的构造器可以满足以下两个条件,代码如下:
复制代码
class Rectangle {
var width : Double
var height : Double
init(width : Double, height : Double) { ①
self.width = width
self.height = height
}
init(W width : Double,H height : Double) { ②
self.width = width
self.height = height
}
init(length : Double) { ③
self.width = length
self.height = length
}
init() { ④
self.width = 640.0
self.height = 940.0
}
}
var rectc1 = Rectangle(width : 320.0, height : 480.0) ⑤
println("长方形:(rectc1.width) x (rectc1.height)")
var rectc2 = Rectangle(W : 320.0, H : 480.0) ⑥
println("长方形:(rectc2.width) x (rectc2.height)")
var rectc3 = Rectangle(length: 500.0) ⑦
println("长方形3:(rectc3.width) x (rectc3.height)")
var rectc4 = Rectangle() ⑧








