Swift4 基礎(chǔ)部分: Extensions(擴(kuò)展)

本文是學(xué)習(xí)《The Swift Programming Language》整理的相關(guān)隨筆,基本的語(yǔ)法不作介紹,主要介紹Swift中的一些特性或者與OC差異點(diǎn)。

系列文章:

Extensions add new functionality to an existing class, 
structure, enumeration, or protocol type. This includes the 
ability to extend types for which you do not have access to 
the original source code (known as retroactive modeling). 
Extensions are similar to categories in Objective-C. (Unlike 
Objective-C categories, Swift extensions do not have names.)

Extensions in Swift can:

Add computed instance properties and computed type properties
Define instance methods and type methods
Provide new initializers
Define subscripts
Define and use new nested types
Make an existing type conform to a protocol
  • Swift中的擴(kuò)展與OC中的類別很相似,闊以用來(lái)擴(kuò)展方法,屬性,同時(shí)還可以提供新的構(gòu)造器,定義下標(biāo),定義與使用新的嵌套類型,使這個(gè)擴(kuò)展實(shí)現(xiàn)某個(gè)協(xié)議。

計(jì)算屬性(Computed Properties)

Extensions can add computed instance properties and computed 
type properties to existing types.
  • 擴(kuò)展可以添加計(jì)算屬性到已有類中。

例子:

extension Double {
    var km:Double {
        return self * 1000.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");

執(zhí)行結(jié)果:

One inch is 0.0254 meters
Three feet is 0.914399970739201 meters

構(gòu)造器(Initializers)

Extensions can add new initializers to existing types.

例子:擴(kuò)展Rect通過(guò)center,size計(jì)算Rect的值

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();
}


// MARK: - 添加一個(gè)擴(kuò)展通過(guò)center,size計(jì)算rect
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));
print(centerRect);

方法(Methods)

Extensions can add new instance methods and type methods to existing types.
  • 擴(kuò)展的方式可以添加新的實(shí)例方法和類方法到該類型。

例子:

extension Int {
    func repetitions(task: () -> Void){
        for index in 0..<self{
            task();
        }
    }
    
    func toBinary() -> String {
        return String(self,radix:2);
    }
    
    // 必須用mutating修飾才能修改自身
    mutating func square() {
        self = self * self
    }
}

3.repetitions(task:{
     print("Hello");
})
print(3.toBinary());

var someInt:Int = 3;
someInt.square();
print(someInt);

執(zhí)行結(jié)果:

Hello
Hello
Hello
11
9

定義下標(biāo)(Subscripts)

Extensions can add new subscripts to an existing type.

例子:

extension Int {
    subscript(digitIndex:Int) -> Int{
        var decimalBase:Int = 1;
        for index in 0..<digitIndex{
            decimalBase *= 10;
        }
        
        return (self / decimalBase) % 10;
    }
}

print(123456[2]);
print(123456[3]);
print(123456[4]);

執(zhí)行結(jié)果:

4
3
2 

嵌套類型(Nested Types)

Extensions can add new nested types to existing classes, structures, and enumerations

例子:

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;
        }
    }
}


print(12345.kind);
print(0.kind);
print((-12345).kind);

執(zhí)行結(jié)果:

positive
zero
negative
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,252評(píng)論 4 61
  • Step 1選摘:只有博學(xué)的人才有融會(huì)貫通的能力(甚至是機(jī)會(huì))。 于是,學(xué)習(xí)的時(shí)候,“莫問(wèn)前程但行好事”是最優(yōu)策略...
    簡(jiǎn)希日課閱讀 233評(píng)論 0 3
  • 背景 我們?cè)陂_發(fā)的時(shí)候肯定會(huì)打一些Log,特別是在調(diào)試代碼或者bug的時(shí)候,我們都會(huì)打一些Log日志來(lái)記錄,但是當(dāng)...
    Only凹凸曼閱讀 2,302評(píng)論 2 6
  • 人畢竟是一種感性生物,沒(méi)有誰(shuí)可以永遠(yuǎn)保持理性思考。 東邪西毒里有一句經(jīng)典臺(tái)詞:從小我就懂得保護(hù)自己,我知道要想不被...
    冰星星閱讀 280評(píng)論 1 0
  • 文/那年沐子 相思苦,相思累, 相思愁斷腸, 片片秋風(fēng)飛。 相思難,相思意, 相思滿心頭, 縷縷青絲悲。
    那年沐子閱讀 310評(píng)論 0 1