extension
来声明extension SomeType {
// 为 SomeType 添加的新功能写到这里
}
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") //One inch is 0.0254 meters
class ClassA{
var a = 0
var b = 0
init(a:Int,b:Int) {
print("a = \(a),b = \(b)")
}
}
let a = ClassA.init(a: 2, b: 2)
extension ClassA{
convenience init(a:Int,b:Int,c:Int) {
self.init(a:a,b:b)
print("a = \(a),b = \(b),c = \(c)")
}
}
let aa = ClassA.init(a: 1, b: 2, c: 3)
//a = 2,b = 2
//a = 1,b = 2
//a = 1,b = 2,c = 3
class ClassA{
var a = 0
var b = 0
init(a:Int,b:Int) {
self.a = a
self.b = b
}
}
extension ClassA{
func sum() -> Int {
return a + b
}
}
let a = ClassA.init(a: 2, b: 3)
print(a.sum())