原文排版 有點(diǎn)讓我蛋疼, 將它的精髓技巧整理一下, 于是就有了本文. (侵刪)
Defer管理程序控制流
defer語句會(huì)推遲包含這個(gè)命令的代碼執(zhí)行,直到當(dāng)前范圍終止。也就是說蛇更,在defer語句中清理邏輯是可以替換的辖源,而且只要離開相應(yīng)的調(diào)用范圍,這段命令就肯定就會(huì)被調(diào)用宁改。這樣可以減少冗余步驟,更重要的是增加安全性。
func deferExample() {
defer {
print("Leaving scope, time to cleanup!")
}
print("Performing some operation...")
}
deferExample()
// Prints:
// Performing some operation...
// Leaving scope, time to cleanup!
Swizzle_method實(shí)現(xiàn)
Swift不必像OC一樣實(shí)現(xiàn)方法對(duì)調(diào), 可以使用下列代碼實(shí)現(xiàn)方法對(duì)調(diào):
import UIKit
class AwesomeClass {
dynamic func originalFunction() -> String {
return "originalFunction"
}
dynamic func swizzledFunction() -> String {
return "swizzledFunction"
}
}
let awesomeObject = AwesomeClass()
print(awesomeObject.originalFunction()) // prints: "originalFunction"
let aClass = AwesomeClass.self
let originalMethod = class_getInstanceMethod(aClass, "originalFunction")
let swizzledMethod = class_getInstanceMethod(aClass, "swizzledFunction")
method_exchangeImplementations(originalMethod, swizzledMethod)
print(awesomeObject.originalFunction()) // prints: "swizzledFunction"
創(chuàng)建全局Helper函數(shù)
全局變量和函數(shù)經(jīng)常被合稱為“壞東西”屹徘,不過事實(shí)是兩者都能讓代碼更干凈,真正的壞東西是全局狀態(tài)磨德。全局函數(shù)經(jīng)常需要全局狀態(tài)來完成相關(guān)工作缘回,因此很容易理解它們?yōu)槭裁磿?huì)有這樣的壞名聲。下面是一些Grand Central Dispatch的helper函數(shù)樣例典挑,不是建立在全局狀態(tài)之上酥宴,而且多少有些語法糖(指計(jì)算機(jī)語言中添加的某種語法,這種語法對(duì)語言的功能并沒有影響您觉,但是更方便程序員使用)的性質(zhì)拙寡。下面我們會(huì)采用dispatch_after函數(shù),用Swift的方式來解包:
用Swift語法來解包C函數(shù)琳水,讓我們的代碼更易于一眼理解肆糕。找到你最喜歡的函數(shù)般堆,試一下吧!只要在正確方法命名上盡責(zé)诚啃,將來程序的維護(hù)者肯定感激我們淮摔。如果我們將上面的方法簽名修改為delay(delay: Double, closure: ()->()),這就成了不負(fù)責(zé)任的方法命名反例始赎,因?yàn)閐ispatch_after需要GCD隊(duì)列和橙,而從名稱中看不出來使用的哪個(gè)隊(duì)列。然而造垛,如果我們使用的代碼庫在主線程所有方法的執(zhí)行上有既定規(guī)范魔招,除非在名稱或評(píng)論上另有指示,delay(delay: Double, closure: ()->())就可以是一個(gè)正確的方法名稱五辽。無論我們?nèi)绾蚊鹔elper函數(shù)办斑,它們都是為了通過包裝樣本代碼節(jié)省時(shí)間,讓代碼更易讀
import Foundation
/**
Executes the closure on the main queue after a set amount of seconds.
- parameter delay: Delay in seconds
- parameter closure: Code to execute after delay
*/
func delayOnMainQueue(delay: Double, closure: ()->()) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), closure)
}
/**
Executes the closure on a background queue after a set amount of seconds.
- parameter delay: Delay in seconds
- parameter closure: Code to execute after delay
*/
func delayOnBackgroundQueue(delay: Double, closure: ()->()) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), closure)
}
//封裝后調(diào)用
delayOnBackgroundQueue(5) {
showView()
}
//封裝前調(diào)用
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)) {
showView()
}