现有的类,结构或枚举类型的功能可以在扩展的帮助下加入。类型的功能可以使用扩展加入,但重写的功能不能使用扩展。
Swift 扩展功能:
扩展用关键字 extension 声明
语法
extension SomeType: SomeProtocol, AnotherProtocol {
// protocol requirements is described here
}
let mix = 30.add + 34.sub
println("Mixed Type is \(mix)")
Addition is 103 Subtraction is 110 Multiplication is 390 Division is 11 Mixed Type is 154
初始化器
Swift 能够灵活地通过扩展新的初始化添加到现有的类型。用户可以添加自己的自定义类型来扩展已定义的类型,额外的初始化选项也是可以的。 扩展仅支持 init(). 而 deinit() 不被扩展支持。
let a = sum(num1: 100, num2: 200)
println("Inside Sum Block:\( a.num1, a.num2)")
let b = diff(no1: 200, no2: 100)
println("Inside Diff Block: \(b.no1, b.no2)")
Inside mult block (100, 200) Inside mult block (200, 100) Inside mult block (300, 500) Inside mult block (300, 100) Inside Sum Block:(100, 200) Inside Diff Block: (200, 100)
方法
新实例方法和类型的方法,可以在扩展的帮助下进一步加入到子类。
4.topics({
println("Inside Extensions Block")
})
3.topics({
println("Inside Type Casting Block")
})
Inside Extensions Block Inside Extensions Block Inside Extensions Block Inside Extensions Block Inside Type Casting Block Inside Type Casting Block Inside Type Casting Block
topics() 函数使用参数是 (summation: () -> ()) 的类型表示该函数不带任何参数 而且它不会返回任何值。调用该函数多次, 块被初始化,并调用 topic()方法初始化。
不同实例方法变形
实例方法时也可以作为扩展声明的变形。
修改自身的结构和计数的方法或它的属性必须标注实例方法变形,就像是从一个原始的实现变形的方法。
var Trial1 = 3.3
Trial1.square()
println("Area of circle is: \(Trial1)")
var Trial2 = 5.8
Trial2.square()
println("Area of circle is: \(Trial2)")
var Trial3 = 120.3
Trial3.square()
println("Area of circle is: \(Trial3)")
Area of circle is: 34.210935 Area of circle is: 105.68006 Area of circle is: 45464.070735
下标
添加新标已声明实例也可以扩展。
2 6 5
嵌套类型
嵌套类型为类,结构和枚举实例,也可在扩展的帮助下进行扩展。
var print: calc {
switch self
{
case 0:
return .add
case 1:
return .sub
case 2:
return .mult
case 3:
return .div
default:
return .anything
}
}
}
func result(numb: [Int]) {
for i in numb {
switch i.print {
case .add:
println(" 10 ")
case .sub:
println(" 20 ")
case .mult:
println(" 30 ")
case .div:
println(" 40 ")
default:
println(" 50 ")
}
}
}
result([0, 1, 2, 3, 4, 7])
10 20 30 40 50 50