class PirateManager {
static let sharedInstance = PirateManager()
/* ... */
}
闭包
如果参数的类型很明显,可以在函数名里可以省略参数类型, 但明确声明类型也是允许的。 代码的可读性有时候是添加详细的信息,而有时候部分重复,根据你的判断力做出选择吧,但前后要保持一致性。
// 省略类型
doSomethingWithClosure() { response in
print(response)
}
// 明确指出类型
doSomethingWithClosure() { response: NSURLResponse in
print(response)
}
// map 语句使用简写
[1, 2, 3].flatMap { String($0) }
如果使用捕捉列表 或 有具体的非 Void返回类型,参数列表应该在小括号内, 否则小括号可以省略。
// 因为使用捕捉列表,小括号不能省略。
doSomethingWithClosure() { [weak self] (response: NSURLResponse) in
self?.handleResponse(response)
}
// 因为返回类型,小括号不能省略。
doSomethingWithClosure() { (response: NSURLResponse) -> String in
return String(response)
}
如果闭包是变量类型,不需把变量值放在括号中,除非需要,如变量类型是可选类型(Optional?), 或当前闭包在另一个闭包内。确保闭包里的所以参数放在小括号中,这样()表示没有参数,Void 表示不需要返回值。
let completionBlock: (success: Bool) -> Void = {
print("Success? (success)")
}
let completionBlock: () -> Void = {
print("Completed!")
}
let completionBlock: (() -> Void)? = nil
数组
基本上不要通过下标直接访问数组内容,如果可能使用.first或.last,因为这些方法是非强制类型并不会奔溃。推荐尽可能使用 for item in items 而不是 for i in 0..n。
不是使用+=或+操作符给数组添加新元素,使用性能较好的.append()或appendContentsOf(),如果需要声明数组基于其他数组并保持不可变类型,使用let myNewArray = [arr1, arr2].flatten(),而不是let myNewArray = arr1 + arr2 。
错误处理
假设一个函数 myFunction 返回类型声明为 String,但是总有可能函数会遇到error,有一种解决方案是返回类型声明为 String?, 当遇到错误的时候返回 nil。
func readFile(withFilename filename: String) -> String? {
guard let file = openFile(filename) else {
return nil
}
let fileContents = file.read()
file.close()
return fileContents
}
func printSomeFile() {
let filename = "somefile.txt"
guard let fileContents = readFile(filename) else {
print("不能打开 (filename).")
return
}
print(fileContents)
}
实际上如果预知失败的原因,我们应该使用Swift 中的 try/catch 。
定义 错误对象 结构体如下:
struct Error: ErrorType {
public let file: StaticString
public let function: StaticString
public let line: UInt
public let message: String
public init(message: String, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) {
self.file = file
self.function = function
self.line = line
self.message = message
}
}








