第二十一章 扩展
c++没有extension语法,一般意义而言,c++完成扩展的功能通过继承和组合来实现。
class Base
{
//存在一些属性和方法
};
class Derived: public Base
{
//添加一些属性和方法
};
class A
{
//部分属性和功能
};
class B
{
//部分属性和功能
};
class C
{
//完成更丰富的功能
private:
A a;
B b;
};
swift有专用的扩展语法:
extension SomeType {
// 为 SomeType 添加的新功能写到这里
}
extension SomeType: SomeProtocol, AnotherProctocol {
// 协议实现写到这里
}
下面是扩展的一些实践
extension Double {
var km: Double { return self * 1_000.0 }
var m : Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
print("One inch is \(oneInch) meters")
let threeFeet = 3.ft
print("Three feet is \(threeFeet) meters")
let twoKillometer = 2.km
let aMarathon = 42.km + 195.m
print("A marathon is \(aMarathon) meters long")
struct Size {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
}
extension Rect {
init(center: Point, size: Size) {
let originX = center.x - size.width / 2
let originY = center.y - size.height / 2
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
extension Int {
func repetitions(task: () -> Void) {
for _ in 0..<self {
task()
}
}
}
3.repetitions {
print("hello")
}
extension Int {
mutating func square() {
self = self * self
}
}
var someInt = 3
someInt.square()