Summary for developers
let-bindings over var-bindings wherever possible优先使用 let 而非 var 可以产生安全清晰的代码。
struct,因为值类型更简单,容易分析。class 才能提供的功能( identity 或 deinitializers)时,再使用 class。继承通常不是使用 class 的好理由,因为多态可以通过协议实现,而重用可以通过组合实现。final by defaultclass 应该用 final 修饰,类中的定义(属性和方法等)也要尽可能使用 final 修饰。 组合通常比继承更合适,选择使用继承则很可能意味着在做出决定时需要更多的思考。
当对接收者来说一样时,参数化类型的方法可以省略接收者的类型参数。省略多余的类型参数让意图更清晰。
struct Composite<T> {
…
func compose(other: Composite) -> Composite {
return Composite(self, other)
}
}
当你遇到某些操作需要通过条件判断去执行,应当尽早地退出判断条件。你可以用 if 声明或使用 guard(推荐)。使用 guard声明时编译器会强制要求你将 return, break 或者 continue 一起搭配使用,否则会产生编译时错误。
guard someArray.isEmpty else {
return
}
// Use someArray here
尽量不要通过强制解包(foo!)来获取关联值,这样很可能会导致运行时崩溃。
推荐使用 if-let ,if let 绑定可选类型产生了更安全的代码。也可以使用可选链。
if let foo = foo {
// Use unwrapped `foo` value in here
} else {
// If appropriate, handle the case where the optional is nil
}
// Call the function if `foo` is not nil. If `foo` is nil, ignore we ever tried to make the call
foo?.callSomethingIfFooIsNotNil()
foo 可能为 nil 时,尽可能使用用 let foo: FooType? 而不是 let foo: FooType!。明确的可选类型产生了更安全的代码。
如果可以,省略只读属性和 subscript 的 get 关键字。
var myGreatProperty: Int {
return 42
}
subscript(index: Int) -> T {
return objects[index]
}
Top-Level 的函数、类型和变量,总是应该指定详尽的权限控制说明符。而在这些函数或类型的内部,可以在合适的地方使用隐式权限控制。
当指定标示符的类型时,冒号要紧跟着标示符,然后空一格再写类型。
class SmallBatchSustainableFairtrade: Coffee { ... }
let timeToCoffee: NSTimeInterval = 2
func makeCoffee(type: CoffeeType) -> Coffee { ... }
let capitals: [Country: City] = [sweden: stockholm]
self when required当调用 self 的属性或方法时,默认隐式引用self,这样保持了简洁性。参数名冲突时等等必要时再加上 self。在(逃逸)闭包里使用 self 凸显了它捕获 self 的语义,参数名冲突时使用 self也是在必要时使用。
关于空行和缩进,推荐使用 XCFormat ( 可在 App Store 搜索下载)。