《从零开始学Swift》学习笔记(Day 39)——构造函数重载
构造函数作为一种特殊方法,也可以重载。 Swift中构造函数可以多个,他们参数列表和返回值可以不同,这些构造函数构成重载。 示例代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 class Rectangle{ varwidth:Double varheight:Double init(width:Double,height:Double){ self.width=width self.height=height } init(Wwidth:Double,Hheight: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 } } varrectc1=Rectangle(width: 320.0 ,height: 480.0 ) print( "长方形:\(rectc1.width)x\(rectc1.height)" ) varrectc2=Rectangle(W: 320.0 ,H: 480.0 ) print( "长方形:\(rectc2.width)x\(rectc2.height)" ) varrectc3=Rectangle(length: 500.0 ) print( "长方形3:\(rectc3.width)x\(rectc3.height)" ) varrectc4=Rectangle() print( "长方形4:\(rectc4.width)x\(rectc4.height)" ) 构造函数代理 为了减少多个构造函数间的代码重复,在定义构造函数时,可以通过调用其他构造函数来完成实例的部分构造过程,这个过程称为构造函数代理。构造函数代理在结构体和类中使用方式是不同,先介绍结构体中构造函数代理。 将上一节的示例修改如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 structRectangle{ varwidth:Double varheight:Double init(width:Double,height:Double){ self.width=width self.height=height } init(Wwidth:Double,Hheight:Double){ self.width=width self.height=height } init(length:Double){ //调用了self.init语句 self.init(W:length,H:length) } init(){ //调用了self.init语句 self.init(width: 640.0 ,height: 940.0 ) } } varrectc1=Rectangle(width: 320.0 ,height: 480.0 ) print( "长方形:\(rectc1.width)x\(rectc1.height)" ) varrectc2=Rectangle(W: 320.0 ,H: 480.0 ) print( "长方形:\(rectc2.width)x\(rectc2.height)" ) varrectc3=Rectangle(length: 500.0 ) print( "长方形3:\(rectc3.width)x\(rectc3.height)" ) varrectc4=Rectangle() print( "长方形4:\(rectc4.width)x\(rectc4.height)" ) 将Rectangle声明为结构体类型,其中也有4个构造函数重载。 这种在同一个类型中通过self.init语句进行调用当前类型其它构造函数,其它构造函数被称为构造函数代理。 类构造函数横向代理 由于类有继承关系,类构造函数代理比较复杂,分为横向代理和向上代理。 横向代理类似于结构体类型构造函数代理,发生在同一类内部,这种构造函数称为便利构造函数(convenience initializers)。 向上代理发生在继承情况下,在子类构造过程中要先调用父类构造函数,初始化父类的存储属性,这种构造函数称为指定构造函数(designated initializers)。 将上面的示例修改如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 class Rectangle{ varwidth:Double varheight:Double init(width:Double,height:Double){ self.width=width self.height=height } init(Wwidth:Double,Hheight:Double){ self.width=width self.height=height } convenienceinit(length:Double){ self.init(W:length,H:length) } convenienceinit(){ self.init(width: 640.0 ,height: 940.0 ) } } varrectc1=Rectangle(width: 320.0 ,height: 480.0 ) print( "长方形:\(rectc1.width)x\(rectc1.height)" ) varrectc2=Rectangle(W: 320.0 ,H: 480.0 ) print( "长方形:\(rectc2.width)x\(rectc2.height)" ) varrectc3=Rectangle(length: 500.0 ) print( "长方形3:\(rectc3.width)x\(rectc3.height)" ) varrectc4=Rectangle() print( "长方形4:\(rectc4.width)x\(rectc4.height)" ) 将Rectangle声明为类,其中也有4个构造函数重载。 本文转自 tony关东升 51CTO博客,原文链接:http://blog.51cto.com/tonyguan/1747009,如需转载请自行联系原作者