本文討論 Alamofire 中使用到的一些 Swift 慣用編程技巧。
單例
單例模式是一種被廣泛運(yùn)用的設(shè)計(jì)模式板丽。一個(gè)設(shè)計(jì)正確的單例類必須保證應(yīng)用的生命周期之內(nèi)在內(nèi)存中有且只能有一個(gè)該類的實(shí)例,這也要求湿右,單例類的實(shí)例化方法必須是線程安全的痰憎。使用 Swift 有若干種方式可以實(shí)現(xiàn)單例類,下面是幾種常見(jiàn)的實(shí)現(xiàn)方式锅纺。
使用帶有明顯 Objective-C 風(fēng)格的 dispatch_once
方式:
class Singleton {
public class var sharedInstance: Singleton {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: Singleton? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = Singleton()
}
return Static.instance!
}
private init() {}
}
在類常量中嵌套一個(gè) struct 也可以完成任務(wù)(這里的 struct 類似于 C 語(yǔ)言中函數(shù)的 static
局部變量):
class Singleton {
public class var sharedInstance: Singleton {
struct Static {
static let instance: Singleton = Singleton()
}
return Static.instance
}
private init() {}
}
實(shí)現(xiàn)單例類的最簡(jiǎn)潔的方式是使用類常量:
class Singleton {
public static let sharedInstance = Singleton();
private init() {}
}
至于類常量的線程安全性掷空,Swift 官方博客上面的一篇文章告訴我們,類常量的初始化工作實(shí)際上是在 dispatch_once
線程中完成的:
The lazy initializer for a global variable (also for static members of structs and enums) is run the first time that global is accessed, and is launched as dispatch_once to make sure that the initialization is atomic. This enables a cool way to use dispatch_once in your code: just declare a global variable with an initializer and mark it private.
Alamofire 正是使用了這種方式實(shí)現(xiàn)單例類。稍有不同的是坦弟,下面的例子使用了一個(gè)匿名閉包來(lái)初始化類常量护锤,這讓我們?cè)趯?shí)例化 Manager 對(duì)象之前可以做一些額外的準(zhǔn)備工作:
// Alamofire: Manager.swift
public class Manager {
public static let sharedInstance: Manager = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
return Manager(configuration: configuration)
}()
}
枚舉
Swift 提供了優(yōu)雅而且功能強(qiáng)大的枚舉類型。在 Swift 的枚舉類型中酿傍,每一個(gè)枚舉項(xiàng)均可以攜帶一個(gè)或者一組關(guān)聯(lián)值(Associated Values):
// Alamofire: NetworkReachabilityManager.swift
public enum NetworkReachabilityStatus {
case Unknown
case NotReachable
case Reachable(ConnectionType)
}
另外烙懦,Swift 也支持具有原始值(Raw Value)的枚舉類型,這種枚舉類型繼承自其他類:
// Alamofire: Error.swift
public enum Code: Int {
case InputStreamReadFailed = -6000
case OutputStreamWriteFailed = -6001
case ContentTypeValidationFailed = -6002
case StatusCodeValidationFailed = -6003
case DataSerializationFailed = -6004
case StringSerializationFailed = -6005
case JSONSerializationFailed = -6006
case PropertyListSerializationFailed = -6007
}
保鏢模式(Bouncer Pattern)
保鏢模式的原則是盡早發(fā)現(xiàn)錯(cuò)誤赤炒,然后將其拒之門外氯析。在 guard
關(guān)鍵字的幫助下,我們可以寫出線性的莺褒、邏輯非常直觀的函數(shù)魄鸦。
示例代碼:
// Alamofire: MultipartFormData.swift
public func appendBodyPart(fileURL fileURL: NSURL, name: String, fileName: String, mimeType: String) {
let headers = contentHeaders(name: name, fileName: fileName, mimeType: mimeType)
//============================================================
// Check 1 - is file URL?
//============================================================
guard fileURL.fileURL else {
let failureReason = "The file URL does not point to a file URL: \(fileURL)"
setBodyPartError(code: NSURLErrorBadURL, failureReason: failureReason)
return
}
//============================================================
// Check 2 - is file URL reachable?
//============================================================
var isReachable = true
if #available(OSX 10.10, *) {
isReachable = fileURL.checkPromisedItemIsReachableAndReturnError(nil)
}
guard isReachable else {
setBodyPartError(code: NSURLErrorBadURL, failureReason: "The file URL is not reachable: \(fileURL)")
return
}
// …
}
guard
關(guān)鍵字是一個(gè)極具爭(zhēng)議性的關(guān)鍵字。有人認(rèn)為 guard
關(guān)鍵字是多余的癣朗,因?yàn)?guard
能做到的事情拾因,if
也可以做到。本文并不打算介入這一爭(zhēng)論旷余。
尾式閉包
尾式閉包(trailing closure)特性幫助寫出簡(jiǎn)短易讀的代碼绢记。當(dāng)函數(shù)的最后一個(gè)參數(shù)是一個(gè)閉包時(shí),我們可以使用下面的語(yǔ)法調(diào)用該函數(shù):
func networkRequest(completion: (response: String) -> Void) {
// function body goes here
}
// here's how you call this function with a trailing closure:
networkRequest() { response in
// trailing closure’s body goes here
}
class 與 struct
在 Swift 中正卧,class
和 struct
兩種類型之間最大的區(qū)別是蠢熄,class
是引用類型,而 struct
是值類型炉旷。下面的兩個(gè)例子對(duì)此做出了說(shuō)明签孔。
class
的例子:
class PersonClass {
var name: String
init(name: String) {
self.name = name
}
}
let personA = PersonClass(name: "Tom")
let personB = personA
personB.name = "Bob"
print(personA.name) // "Bob"
print(personB.name) // "Bob"
struct
的例子:
struct PersonStruct {
var name: String
init(name: String) {
self.name = name
}
}
let personA = PersonStruct(name: "Tom")
let personB = personA
personB.name = "Bob"
print(personA.name) // "Tom"
print(personB.name) // "Bob"
一般而言,需要處理復(fù)雜的數(shù)據(jù)結(jié)構(gòu)時(shí)窘行,使用 class
饥追;需要封裝少量簡(jiǎn)單的數(shù)值而且期望在復(fù)制操作中進(jìn)行值拷貝時(shí),使用 struct
罐盔。
GCD 與 NSOperation
GCD (Grand Central Dispatch)和 NSOperation 是 Cocoa 框架提供的兩種并發(fā)編程技術(shù)但绕。GCD 在 C 語(yǔ)言層面實(shí)現(xiàn)了并發(fā)編程的基礎(chǔ)設(shè)施,NSOperation 則是對(duì) GCD 的上層封裝惶看。想要講清楚這兩個(gè)概念需要不小的篇幅捏顺,本文不打算展開(kāi)討論。具體的細(xì)節(jié)請(qǐng)參考相關(guān)技術(shù)文檔:
(未完)