class Food {
var name: String
init(name: String) {
self.name = name
}
convenience init() {
self.init(name: "[Unnamed]")
}
}便利构造器通过convenience关键字声明,可以看到,便利构造器是通过调用指定构造器来进行构造的。这也就是一个关键的概念:横向代理。class Base{
var baseVar:String
init(baseInput:String){
baseVar = baseInput
}
convenience init(){
self.init(baseInput:"")
}
}
class Sub:Base{
var subVar:String;
init(subInput:String,baseInput:String){
subVar = subInput
super.init(baseInput:baseInput)//这里是规则1.1
}
convenience init(conSubInput:String){
self.init(subInput:conSubInput,baseInput:"")//这里是规则1.2
}
convenience init(){
self.init(conSubInput:"")//这里是规则1.3,因为调用了另外一个便利构造器,而另外一个便利构造器以调用指定构造器结束
}
}class Base{
var baseVar:String
init(baseInput:String){
baseVar = baseInput
}
convenience init(){
self.init(baseInput:"basevar")
}
}
class Sub:Base{
var subVar:String = "subvar";
}这里子类没有定义任何构造器,所以满足规则2.1,2.1,将继承所有父类的指定构造器和便利构造器var instance1 = Sub() var instance2 = Sub(baseInput:"newBaseVar")
class Base{
var baseVar:String
init(baseInput:String){
baseVar = baseInput
}
init(firstPart:String,secondPart:String){
baseVar = firstPart + secondPart
}
convenience init(){
self.init(baseInput:"basevar")
}
}
class Sub:Base{
var subVar:String;
init(subInput:String,baseInput:String){
subVar = subInput
super.init(baseInput)
}
}var instance = Sub(subInput:"subvar",baseInput:"basevar")
class Base{
var baseVar:String
init(baseInput:String){
baseVar = baseInput
}
}
class Sub:Base{
var subVar:String;
func subPrint(){
println("现在可以调用实例方法了")
}
init(subInput:String,baseInput:String){
subVar = subInput
super.init(baseInput:baseInput)
//这里就完成了阶段一
self.subVar = subInput + "123"//此时可以调用self
subPrint()//此时也可以调用实例方法了
}
}总得来说:当类的实例的内存被初始化完成,也就是调用super.init()之后,就完成了阶段一了。class Food {
var name: String
init(name: String) {
self.name = name
}
convenience init() {
self.init(name: "[Unnamed]")
}
}
class RecipeIngredient: Food {
var quantity: Int
init(name: String, quantity: Int) {
self.quantity = quantity
super.init(name: name)
}
override convenience init(name: String) {
self.init(name: name, quantity: 1)
}
}
class ShoppingListItem: RecipeIngredient {
var purchased = false
var description: String {
var output = "\(quantity) x \(name.lowercaseString)" {
output += purchased ? " YES" : " NO"
return output
}
}这个构造器链的关系如图原文:http://blog.csdn.net/hello_hwc/article/details/41276359