// 擴(kuò)展為現(xiàn)有的類晓淀、結(jié)構(gòu)體怜瞒、枚舉類型线罕、或協(xié)議添加了新功能止潮。這也包括了為無(wú)訪問(wèn)權(quán)限的源代碼擴(kuò)展類型的能力(即所謂的逆向建模)。擴(kuò)展和 Objective-C 中的分類類似钞楼。(與 Objective-C 的分類不同的是喇闸,Swift 的擴(kuò)展沒(méi)有名字。)
擴(kuò)展的語(yǔ)法(extension)
extension SomeType {
// new functionality to add to SomeType goes here
}
// 擴(kuò)展可以使已有的類型遵循一個(gè)或多個(gè)協(xié)議询件。在這種情況下燃乍,協(xié)議名的書寫方式與類或結(jié)構(gòu)體完全一樣
extension SomeType: SomeProtocol, AnotherProtocol {
// implementation of protocol requirements goes here
}
計(jì)算屬性
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")
// Prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
print("Three feet is \(threeFeet) meters")
// Prints "Three feet is 0.914399970739201 meters"
let aMarathon = 42.km + 195.m
print("A marathon is \(aMarathon) meters long")
// Prints "A marathon is 42195.0 meters long"
初始化器
// 擴(kuò)展可向已有的類型添加新的初始化器。這允許你擴(kuò)展其他類型以使初始化器接收你的自定義類型作為形式參數(shù)宛琅,或提供該類型的原始實(shí)現(xiàn)中未包含的額外初始化選項(xiàng)刻蟹。
// 擴(kuò)展能為類添加新的便捷初始化器,但是不能為類添加指定初始化器或反初始化器嘿辟。指定初始化器和反初始化器 必須由原來(lái)類的實(shí)現(xiàn)提供舆瘪。 (無(wú)需寫 convenience 因?yàn)橹荒芴砑有碌谋憬莩跏蓟?
//
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()
}
let defaultRect = Rect()
let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0),
size: Size(width: 5.0, height: 5.0))
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)
}
}
let centerRect = Rect(center: Point(x: 4.0, y: 4.0),
size: Size(width: 3.0, height: 3.0))
// centerRect's origin is (2.5, 2.5) and its size is (3.0, 3.0)
方法
extension Int {
func repetitions(task: () -> Void) {
for _ in 0..<self {
task()
}
}
}
3.repetitions({
print("Hello!")
})
// Hello!
// Hello!
// Hello!
異變實(shí)例方法(允許在方法內(nèi)修改值的方法)
extension Int {
mutating func square() {
self = self * self
}
}
var someInt = 3
someInt.square()
// someInt is now 9
下標(biāo)
extension Int {
subscript(digitIndex: Int) -> Int {
var decimalBase = 1
for _ in 0..<digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
746381295[0]
// returns 5
746381295[1]
// returns 9
746381295[2]
// returns 2
746381295[8]
// returns 7
內(nèi)嵌類型
extension Int {
enum Kind {
case Negative, Zero, Positive
}
var kind: Kind {
switch self {
case 0:
return .Zero
case let x where x > 0:
return .Positive
default:
return .Negative
}
}
}
func printIntegerKinds(numbers: [Int]) {
for number in numbers {
switch number.kind {
case .Negative:
print("- ", terminator: "")
case .Zero:
print("0 ", terminator: "")
case .Positive:
print("+ ", terminator: "")
}
}
print("")
}
printIntegerKinds([3, 19, -27, 0, -6, 0, 7])
// Prints "+ + - 0 - 0 +"