1、Swift中的扩展,在原始类型(类、结构体、枚举)的基础上,添加新功能,轻量级的继承机制,即使原始类型被限制继承,仍然可以扩展
2、声明扩展
extension 类型名 {
//添加新功能
}
类型:类、结构体、枚举、整型、浮点型、布尔型、字符串(本质上也是结构体)型等
新功能:实例计算属性、静态计算属性、实例方法、静态方法、构造函数、下标
3、扩展计算属性,不能定义存储属性
extensionInt{
varerrorMessage :String{
varerrorStr =""
switch(self) {
case-7:
errorStr ="没有数据"
case-6:
errorStr ="日期没有输入"
default:
errorStr =""
}
returnerrorStr
}
}
letmessage = (-7).errorMessage
print(message)
4、扩展方法
extensionDouble{
staticvarinterestRate :Double=0.0668
funcinterestBy1() ->Double{
returnself* Double.interestRate
}
mutatingfuncinterestBy2() {
self=self* Double.interestRate
}
staticfuncinterestBy3(amount :Double) ->Double{
returninterestRate * amount
}
}
letinterest1 = (10_000.00).interestBy1()
print(interest1)
varinterest2 =10_000.00
interest2.interestBy2()
print(interest2)
varinterest3 = Double.interestBy3(amount:10_000.00)
print(interest3)
5、扩展构造函数
值类型扩展构造函数
structRectangle {
varwidth :Double
varheight :Double
init(width :Double, height :Double) {
self.width= width
self.height= height
}
}
extensionRectangle{
init(length :Double) {
self.init(width: length, height: length)
}
}
varrect =Rectangle(width:320.0, height:480.0)
print(rect.height)
varsquare =Rectangle(length:500.0)
print(square.width)
引用类型扩展构造函数
扩展类的时候,能像类中添加新的便利构造函数,不能添加指定构造函数和析构函数
classPerson {
varname :String
varage :Int
funcdescription() ->String{
return"\(name)\(age)"
}
init(name :String, age :Int) {
self.name = name
self.age = age
}
}
extensionPerson{
convenienceinit(name :String) {
self.init(name : name, age :8)
}
}
letp1 = Person(name:"Mary")
print(p1.description())
letp2 = Person(name:"Tony", age:28)
print(p2.description())
6、扩展下标(字符串按照下标访问字符的功能)
extensionString{
subscript(index :Int) ->String{
ifindex >self.characters.count{
return""
}
varc :String=""
vari =0
forcharacterinself.characters{
if(i == index) {
c =String(character)
break
}
i +=1
}
returnc
}
}
lets ="The quick brown fox jumps over the lazy dog"
print(s[0])
print("ABC"[2])
7、扩展Array,计算元素的和
extensionArray{
funcsum() ->Int{
if!(self[0]isInt) {
return0
}
varsum =0
forvalueinself{
sum += valueas!Int
}
returnsum
}
}
letarray = [1,2,3,4,5]
print(array.sum())
letotherArray = ["StringValue"]
print(otherArray.sum())