大佬教程收集整理的这篇文章主要介绍了《从零开始学Swift》学习笔记(Day 39)――构造函数重载,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_674_18@
原创文章,欢迎转载。转载请注明:关东升的博客@H_674_18@
@H_674_18@
Swift@H_674_18@中构造函数可以多个,他们参数列表和返回值可以不同,这些构造函数构成重载。@H_674_18@
classRectangle{ 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)")
@H_674_18@
@H_674_18@
为了减少多个构造函数间的代码重复,在定义构造函数时,可以通过调用其他构造函数来完成实例的部分构造过程,这个过程称为@H_674_18@构造函数代理@H_674_18@。构造函数代理在结构体和类中使用方式是不同,先介绍结构体中构造函数代理。@H_674_18@
structRectangle{ varwidth:Double varheight:Double init(width: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,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)")
@H_674_18@
将@H_674_18@Rectangle@H_674_18@@H_674_18@声明为结构体类型,其中也有@H_674_18@4@H_674_18@个构造函数重载。@H_674_18@
这种在同一个类型中通过@H_674_18@self.init@H_674_18@@H_674_18@语句进行调用当前类型其它构造函数,其它构造函数被称为构造函数代理。@H_674_18@
@H_674_18@
由于类有继承关系,类构造函数代理比较复杂,分为横向代理和向上代理。@H_674_18@
横向代理@H_674_18@类似于结构体类型构造函数代理,发生在同一类内部,这种构造函数称为@H_674_18@便利构造函数@H_674_18@(@H_674_18@convenience initializers)。@H_674_18@
向上代理@H_674_18@发生在继承情况下,在子类构造过程中要先调用父类构造函数,初始化父类的存储属性,这种构造函数称为@H_674_18@指定构造函数@H_674_18@(@H_674_18@designated initializers)。@H_674_18@
classRectangle{ varwidth:Double varheight:Double init(width:Double,Hheight:DoublE){ self.width=width self.height=height } convenienceinit(length:DoublE){ self.init(W:length,H:length) } convenienceinit(){ self.init(width:640.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)")
@H_674_18@
将@H_674_18@Rectangle@H_674_18@@H_674_18@声明为类,其中也有@H_674_18@4@H_674_18@个构造函数重载。@H_674_18@
@H_674_18@
欢迎关注关东升新浪微博@H_674_18@@tony_@H_674_18@关东升。@H_674_18@
@H_674_18@关注智捷课堂微信公共平台,了解最新技术文章、图书、教程信息@H_674_18@
以上是大佬教程为你收集整理的《从零开始学Swift》学习笔记(Day 39)――构造函数重载全部内容,希望文章能够帮你解决《从零开始学Swift》学习笔记(Day 39)――构造函数重载所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。