1. 程式人生 > >Swift 擴充套件(十七)

Swift 擴充套件(十七)

擴充套件 (Extensions)

向一個已有的類、結構體或列舉型別新增新功能,包括再沒有獲取原始碼的情況下擴充套件型別的能力(逆向建模)

1.語法

使用關鍵字 extension
extension SomeType {
    // new functionality to add to SomeType goes here
}
一個擴充套件可以擴充套件一個已有的型別,使其能夠適配一個或多個協議,此時介面的名字應該完全按照類或結構體的名字進行書寫
extension SomeType: SomeProtocol, AnotherProtocol {
    // implementation of protocol requirements goes here
}

2.計算型屬性

擴充套件可向已有型別新增計算型例項屬性和計算型型別屬性
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
println("One inch is \(oneInch) meters")
// prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
println("Three feet is \(threeFeet) meters")
// prints "Three feet is 0.914399970739201 meters"

let aMarathon = 42.km + 195.m
println("A marathon is \(aMarathon) meters long")
// prints "A marathon is 42195.0 meters long"

3.構造器

擴充套件可向已有型別新增新的構造器。可以擴充套件其他型別,將自己定製的型別作為構造器引數,或者提供該型別原始沒有提供的額外選項
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)

4.方法

擴充套件可以向已有型別新增新的例項方法和型別方法
// 向Int新增repetitions方法,使用一個 ()->() 型別的簡單引數,標明函式沒有引數沒有返回值,之後對任意整數呼叫該方法,多次執行某任務
extension Int {
    func repetitions(task: () -> ()) {
        for i in 0..self {
            task()
        }
    }
}

3.repetitions({
    println("Hello!")
    })
// Hello!
// Hello!
// Hello!

// 使用trailing閉包呼叫
3.repetitions {
    println("Goodbye!")
}
// Goodbye!
// Goodbye!
// Goodbye!

4.1修改例項方法

通過擴充套件也可以修改例項本身的方法,結構體和列舉型別中修改self或其屬性的方法必須將該方法標註為mutating,正如來自原始實現的修改方法一樣
extension Int {
    mutating func square() {
        self = self * self
    }
}
var someInt = 3
someInt.square()
// someInt is now 9

5.下標

擴充套件可以向一個已有型別新增新的下標
// 向Int型別新增一個整型下標,下標[n]返回十進位制陣列從右向左數的第n個數字
extension Int {
    subscript(digitIndex: Int) -> Int {
        var decimalBase = 1
            for _ in 1...digitIndex {
                decimalBase *= 10
            }
            return (self / decimalBase) % 10
    }
}
746381295[0]
// returns 5
746381295[1]
// returns 9
746381295[2]
// returns 2
746381295[8]
// returns 7


746381295[9]
// returns 0, as if you had requested:
0746381295[9]

6.巢狀型別

擴充套件可以向已有的類、結構體和列舉新增新的巢狀型別
// 向Character新增新的巢狀列舉Kind,表示特定字元的型別,新增一個新的計算例項屬性kind,返回合適的Kind列舉成員
extension Character {
    enum Kind {
        case Vowel, Consonant, Other
    }
    var kind: Kind {
    switch String(self).lowercaseString {
    case "a", "e", "i", "o", "u":
        return .Vowel
    case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
    "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
        return .Consonant
    default:
        return .Other
        }
    }
}

func printLetterKinds(word: String) {
    println("'\(word)' is made up of the following kinds of letters:")
    for character in word {
        switch character.kind {
        case .Vowel:
            print("vowel ")
        case .Consonant:
            print("consonant ")
        case .Other:
            print("other ")
        }
    }
    print("\n")
}
printLetterKinds("Hello")
// 'Hello' is made up of the following kinds of letters:
// consonant vowel consonant consonant vowel