Protocol Oriented Programming in Swift

下列內(nèi)容是摘錄Reference的文章而生成的讀書筆記秋度。

Protocol v.s. Base Class

  • Multiple Inheritance. You mostly start with single class inheritance but then you realize that you need some more functionality in your class from some different class. This makes you lean towards multiple inheritance which is not supported by most programming languages and leads to undesired complexity.
  • Protocols can be adopted by classes, structs and enums. Base classes and inheritance are restricted to class types.
  • As classes are reference types passing them around in functions can cause unexpected behavior especially if you are working in a multi threaded environment.
  • Unit Test. Due to tight coupling of classes with one another it becomes difficult to write unit tests for a single class.

Protocol v.s. Simple Category/Extension

Protocol makes codes more readable and organizable. And it also provides more access control, since functions in category/extension are accessable for class instances.

Let’s say your product manager comes over and says, “We want a view that when you click a button, it starts shaking.” This is a very common animation with password fields for example – when the user enters the wrong password, it might shake. So we can use the UI extension below to add shake to all UIViews.

extension UIView {

    func shake() {
        let animation = CABasicAnimation(keyPath: "position")
        animation.duration = 0.05
        animation.repeatCount = 5
        animation.autoreverses = true
        animation.fromValue = NSValue(CGPoint: CGPointMake(self.center.x - 4.0, self.center.y))
        animation.toValue = NSValue(CGPoint: CGPointMake(self.center.x + 4.0, self.center.y))
        layer.addAnimation(animation, forKey: "position")
    }
}

If you have done this much for categories and extending UI views, you might have had better experience. It becomes this Frankenstein garbage place where you start adding a shake and then someone comes and says, “We want a dimmable view”. Then you add a dim function and then there is some other random function. It becomes this long, unreadable, hard-to-find garbage file with all these random things that UI view could do, but only maybe one or two things need to do that.

It is not clear what the intention is. How can we change this?

This is a talk about protocol-oriented programming, so we are going to use protocols. Let’s create a Shakeable protocol:

protocol Shakeable { }

extension Shakeable where Self: UIView {

    func shake() {
        // implementation code
    }
}

With protocol extensions, you can constrain them to specific classes. In this case, I can take out my shake function, and, with the category, I can say that only things that conform to this protocol, only UI views, will have this function.

Similarly, we could create the following protocol.

protocol ReusableView: class {}

extension ReusableView where Self: UIView {

    static var reuseIdentifier: String {
        return String(self)
    }
}
protocol NibLoadableView: class { }

extension NibLoadableView where Self: UIView {

    static var nibName: String {
        return String(self)
    }
}

References

How Protocol Oriented Programming in Swift saved my day?

Beyond Crusty: Real-World Protocols

Raywenderlich: Introducing Protocol-Oriented Programming in Swift 3

Practical Protocol-Oriented-Programming

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末欧漱,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子挎峦,更是在濱河造成了極大的恐慌,老刑警劉巖缺亮,帶你破解...
    沈念sama閱讀 212,816評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件澈侠,死亡現(xiàn)場離奇詭異,居然都是意外死亡铅辞,警方通過查閱死者的電腦和手機(jī)厌漂,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,729評論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來斟珊,“玉大人桩卵,你說我怎么就攤上這事”侗觯” “怎么了?”我有些...
    開封第一講書人閱讀 158,300評論 0 348
  • 文/不壞的土叔 我叫張陵胜嗓,是天一觀的道長高职。 經(jīng)常有香客問我,道長辞州,這世上最難降的妖魔是什么怔锌? 我笑而不...
    開封第一講書人閱讀 56,780評論 1 285
  • 正文 為了忘掉前任,我火速辦了婚禮变过,結(jié)果婚禮上埃元,老公的妹妹穿的比我還像新娘。我一直安慰自己媚狰,他們只是感情好岛杀,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,890評論 6 385
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著崭孤,像睡著了一般类嗤。 火紅的嫁衣襯著肌膚如雪糊肠。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 50,084評論 1 291
  • 那天遗锣,我揣著相機(jī)與錄音货裹,去河邊找鬼。 笑死精偿,一個胖子當(dāng)著我的面吹牛弧圆,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播笔咽,決...
    沈念sama閱讀 39,151評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼搔预,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了拓轻?” 一聲冷哼從身側(cè)響起斯撮,我...
    開封第一講書人閱讀 37,912評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎扶叉,沒想到半個月后勿锅,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,355評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡枣氧,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,666評論 2 327
  • 正文 我和宋清朗相戀三年溢十,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片达吞。...
    茶點(diǎn)故事閱讀 38,809評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡张弛,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出酪劫,到底是詐尸還是另有隱情吞鸭,我是刑警寧澤,帶...
    沈念sama閱讀 34,504評論 4 334
  • 正文 年R本政府宣布覆糟,位于F島的核電站刻剥,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏滩字。R本人自食惡果不足惜造虏,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,150評論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望麦箍。 院中可真熱鬧漓藕,春花似錦、人聲如沸挟裂。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽诀蓉。三九已至嫩与,卻和暖如春寝姿,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背划滋。 一陣腳步聲響...
    開封第一講書人閱讀 32,121評論 1 267
  • 我被黑心中介騙來泰國打工饵筑, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人处坪。 一個月前我還...
    沈念sama閱讀 46,628評論 2 362
  • 正文 我出身青樓根资,卻偏偏與公主長得像,于是被迫代替她去往敵國和親同窘。 傳聞我的和親對象是個殘疾皇子玄帕,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,724評論 2 351

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