<h1><details>
<summary>Swift 編碼規范</summary>
A guide to our Swift style and conventions.
</details></h1>
<details><summary>按大概的先后順序,本文嘗試做到以下幾點:</summary>
This is an attempt to encourage patterns that accomplish the following goals (in
rough priority order):
</details>
- <details><summary>增進精確,減少程序員犯錯的可能</summary>Increased rigor, and decreased likelihood of programmer error</details>
- <details><summary>明確意圖</summary>Increased clarity of intent</details>
- <details><summary>減少冗余</summary>Reduced verbosity</details>
- <details><summary>減少關于美的爭論</summary>Fewer debates about aesthetics</details>
<details>
<summary>如果你有什么建議,請看我們的 <a href="./CONTRIBUTING.md">貢獻導引</a>,然后開個 <code>pull request</code>. :zap:
</summary>
If you have suggestions, please see our contribution guidelines,
then open a pull request. :zap:
</details>
<h3><details><summary>留空白</summary>Whitespace</details></h3>
<ul>
<li><details><summary>用 tab,而非 空格</summary>Tabs, not spaces.</details></li>
<li><details><summary>文件結束時留一空行</summary>End files with a newline.</details></li>
<li><details><summary>用足夠的空行把代碼分割成合理的塊</summary>Make liberal use of vertical whitespace to divide code into logical chunks.</details></li>
<li><details><summary>不要在一行結尾留下空白</summary>Don’t leave trailing whitespace.</details>
<ul><li><details><summary>千萬別在空行留下縮進</summary>Not even leading indentation on blank lines.</details></li></ul>
</li>
</ul>
<h3><details>
<summary>能用 <code>let</code> 盡量用 <code>let</code> 而不是 <code>var</code></summary>
Prefer let
-bindings over var
-bindings wherever possible
</details></h3>
<details>
<summary>
盡可能的用 <code>let foo = ...</code> 而不是 <code>var foo = ...</code> (并且包括你疑惑的時候)。萬不得已的時候,再用 <code>var</code> (就是說:你 <i>知道</i> 這個值會改變,比如:有 <code>weak</code> 修飾的存儲變量)。
</summary>
Use let foo = …
over var foo = …
wherever possible (and when in doubt). Only use var
if you absolutely have to (i.e. you know that the value might change, e.g. when using the weak
storage modifier).
</details>
<details>
<summary>
<i>理由:</i> 這倆關鍵字 無論意圖還是意義 都很清楚了,但是 <code>let</code> 可以產生安全清晰的代碼。
</summary>
Rationale: The intent and meaning of both keywords are clear, but let-by-default results in safer and clearer code.
</details>
<br />
<details>
<summary>
<code>let</code> 保障它的值的永遠不會變,對程序猿也是個 <i>清晰的標記</i>。因此對于它的用法,之后的代碼可以做個強而有力的推斷。</summary>
A let
-binding guarantees and clearly signals to the programmer that its value will never change. Subsequent code can thus make stronger assumptions about its usage.
</details>
<details>
<summary>
理解代碼也更容易了。不然一旦你用了 <code>var</code>,還要去推測值會不會變,這時候你就不得不人肉去檢查。
</summary>
It becomes easier to reason about code. Had you used var
while still making the assumption that the value never changed, you would have to manually check that.
</details>
<details>
<summary>
相應地,無論何時你看到 <code>var</code>,就假設它會變,并問自己為啥。
</summary>
Accordingly, whenever you see a var
identifier being used, assume that it will change and ask yourself why.
</details>
<h3><details><summary>
盡早地 <code>return</code> 或者 <code>break</code></summary>
Return and break early</details></h3>
<details>
<summary>當你遇到某些操作需要通過條件判斷去執行,應當盡早地退出判斷條件:你不應該用下面這種寫法</summary>
When you have to meet certain criteria to continue execution, try to exit early. So, instead of this:
</details>
if n.isNumber {
// Use n here
} else {
return
}
<details><summary>用這個:</summary>use this:</details>
guard n.isNumber else {
return
}
// Use n here
<details>
<summary>或者你也可以用 <code>if</code> 聲明,但是我們推薦你使用 <code>guard</code></summary>
You can also do it with if
statement, but using guard
is prefered
</details>
<details>
<summary><i>理由:</i> 你一但聲明 <code>guard</code> 編譯器會強制要求你和 <code>return</code>, <code>break</code> 或者 <code>continue</code> 一起搭配使用,否則會產生一個編譯時的錯誤。</summary>
because guard
statement without return
, break
or continue
produces a compile-time error, so exit is guaranteed.
</details>
<h3><details><summary>避免對 可選類型 強解包</summary>Avoid Using Force-Unwrapping of Optionals</details></h3>
<details><summary>如果你有個 <code>FooType?</code> 或 <code>FooType!</code> 的 <code>foo</code>,盡量不要強行展開它(<code>foo!</code>)以得到它的關聯值。</summary>
If you have an identifier foo
of type FooType?
or FooType!
, don't force-unwrap it to get to the underlying value (foo!
) if possible.
</details>
<details><summary>取而代之的,推薦這樣:</summary>Instead, prefer this:</details>
if let foo = foo {
// Use unwrapped `foo` value in here
} else {
// If appropriate, handle the case where the optional is nil
}
<details><summary>或者使用可選鏈,比如:</summary>
Alternatively, you might want to use Swift's Optional Chaining in some of these cases, such as:
</details>
// Call the function if `foo` is not nil. If `foo` is nil, ignore we ever tried to make the call
foo?.callSomethingIfFooIsNotNil()
<details><summary><i>理由:</i> <code>if let</code> 綁定可選類型產生了更安全的代碼,強行展開很可能導致運行時崩潰。</summary>
Rationale: Explicit if let
-binding of optionals results in safer code. Force unwrapping is more prone to lead to runtime crashes.
</details>
<h3><details><summary>避免隱式解析的可選類型</summary>Avoid Using Implicitly Unwrapped Optionals</details></h3>
<details><summary>如果 foo 可能為 <code>nil</code> ,盡可能的用 <code>let foo: FooType?</code> 代替 <code>let foo: FooType!</code>(注意:一般情況下,<code>?</code> 可以代替 <code>!</code>)</summary>
Where possible, use let foo: FooType?
instead of let foo: FooType!
if foo
may be nil (Note that in general, ?
can be used instead of !
).
</details>
<details><summary><i>理由:</i> 明確的可選類型產生了更安全的代碼。隱式解析的可選類型也可能會掛。</summary>
Rationale: Explicit optionals result in safer code. Implicitly unwrapped optionals have the potential of crashing at runtime.
</details>
<h3><details><summary>對于只讀屬性和 <code>subscript</code>,選用隱式的 getters 方法</summary>
Prefer implicit getters on read-only properties and subscripts
</details></h3>
<details><summary>如果可以,省略只讀屬性和 <code>subscript</code> 的 <code>get</code> 關鍵字</summary>
When possible, omit the get
keyword on read-only computed properties and
read-only subscripts.</details>
<details><summary>所以應該這樣寫:</summary>So, write these:</details>
var myGreatProperty: Int {
return 4
}
subscript(index: Int) -> T {
return objects[index]
}
<details><summary>……而不是:</summary>… not these:</details>
var myGreatProperty: Int {
get {
return 4
}
}
subscript(index: Int) -> T {
get {
return objects[index]
}
}
<details><summary><i>理由:</i> 第一個版本的代碼意圖已經很清楚了,并且用了更少的代碼</summary>
Rationale: The intent and meaning of the first version are clear, and results in less code.
</details>
<h3><details><summary>對于頂級定義,永遠明確的列出權限控制</summary>Always specify access control explicitly for top-level definitions</details></h3>
<details><summary>頂級函數,類型和變量,永遠應該有著詳盡的權限控制說明符</summary>
Top-level functions, types, and variables should always have explicit access control specifiers:
</details>
public var whoopsGlobalState: Int
internal struct TheFez {}
private func doTheThings(things: [Thing]) {}
<details><summary>然而在這些函數/類型的內部,可以在合適的地方使用隱式權限控制:</summary>However, definitions within those can leave access control implicit, where appropriate:
</details>
internal struct TheFez {
var owner: Person = Joshaber()
}
<details><summary><i>理由:</i> 頂級定義指定為 <code>internal</code> 很少有恰當的,要明確的確保經過了仔細的判斷。在定義的內部重用同樣的權限控制說明符就顯得重復,而且默認的通常是合理的。</summary>
Rationale: It's rarely appropriate for top-level definitions to be specifically internal
, and being explicit ensures that careful thought goes into that decision. Within a definition, reusing the same access control specifier is just duplicative, and the default is usually reasonable.
</details>
<h3><details><summary>當指定一個類型時,把 冒號和標識符 連在一起</summary>
When specifying a type, always associate the colon with the identifier
</details></h3>
<details><summary>當指定標示符的類型時,冒號要緊跟著標示符,然后空一格再寫類型</summary>
When specifying the type of an identifier, always put the colon immediately
after the identifier, followed by a space and then the type name.
</details>
class SmallBatchSustainableFairtrade: Coffee { ... }
let timeToCoffee: NSTimeInterval = 2
func makeCoffee(type: CoffeeType) -> Coffee { ... }
<details><summary><i>理由:</i> 類型區分號是對于標示符來說的,所以要跟它連在一起。</summary>
Rationale: The type specifier is saying something about the identifier so
it should be positioned with it.
</details>
<br />
<details><summary>此外,指定字典類型時,鍵類型后緊跟著冒號,接著加一個空格,之后才是值類型。</summary>
Also, when specifying the type of a dictionary, always put the colon immediately after the key type, followed by a space and then the value type.
</details>
let capitals: [Country: City] = [sweden: stockholm]
<h3><details><summary>需要時才寫上 <code>self</code></summary>
Only explicitly refer to self
when required
</details></h3>
<details><summary>當調用 <code>self</code> 的屬性或方法時,默認隱式引用<code>self</code>:</summary>
When accessing properties or methods on self
, leave the reference to self
implicit by default:
</details>
private class History {
var events: [Event]
func rewrite() {
events = []
}
}
<details><summary>必要的時候再加上 <code>self</code>, 比如在(逃逸)閉包里,或者 參數名沖突了:</summary>
Only include the explicit keyword when required by the language—for example, in a closure, or when parameter names conflict:
</details>
extension History {
init(events: [Event]) {
self.events = events
}
var whenVictorious: () -> () {
return {
self.rewrite()
}
}
}
<details><summary><i>原因:</i> 在閉包里用 <code>self</code> 更加凸顯它捕獲 <code>self</code> 的語義,別處避免了冗長</summary>
Rationale: This makes the capturing semantics of self
stand out more in closures, and avoids verbosity elsewhere.
</details>
<h3><details><summary>首選 <code>struct</code> 而非 <code>class</code></summary>
Prefer structs over classes
</details></h3>
<details><summary>除非你需要 <code>class</code> 才能提供的功能(比如 identity 或 <code>deinit</code>ializers),不然就用 <code>struct</code></summary>
Unless you require functionality that can only be provided by a class (like identity or deinitializers), implement a struct instead.
</details>
<details><summary>要注意到繼承通常 <strong>不</strong> 是用 類 的好理由,因為 多態 可以通過 協議 實現,重用 可以通過 組合 實現。</summary>
Note that inheritance is (by itself) usually not a good reason to use classes, because polymorphism can be provided by protocols, and implementation reuse can be provided through composition.
</details>
<details><summary>比如,這個類的分級</summary>
For example, this class hierarchy:
</details>
class Vehicle {
let numberOfWheels: Int
init(numberOfWheels: Int) {
self.numberOfWheels = numberOfWheels
}
func maximumTotalTirePressure(pressurePerWheel: Float) -> Float {
return pressurePerWheel * Float(numberOfWheels)
}
}
class Bicycle: Vehicle {
init() {
super.init(numberOfWheels: 2)
}
}
class Car: Vehicle {
init() {
super.init(numberOfWheels: 4)
}
}
<details><summary>可以重構成醬紫:</summary>
could be refactored into these definitions:
</details>
protocol Vehicle {
var numberOfWheels: Int { get }
}
func maximumTotalTirePressure(vehicle: Vehicle, pressurePerWheel: Float) -> Float {
return pressurePerWheel * Float(vehicle.numberOfWheels)
}
struct Bicycle: Vehicle {
let numberOfWheels = 2
}
struct Car: Vehicle {
let numberOfWheels = 4
}
<details><summary><i>理由:</i> 值類型更簡單,容易分析,并且 <code>let</code> 關鍵字的行為符合預期。</summary>
Rationale: Value types are simpler, easier to reason about, and behave as expected with the let
keyword.
</details>
<h3><details><summary>默認 <code>class</code> 為 <code>final</code></summary>
Make classes final
by default
</details></h3>
<details><summary><code>class</code> 應該用 <code>final</code> 修飾,并且只有在繼承的有效需求已被確定時候才能去使用子類。即便在這種情況(前面提到的使用繼承的情況)下,根據同樣的規則(<code>class</code> 應該用 <code>final</code> 修飾的規則),類中的定義(屬性和方法等)也要盡可能的用 <code>final</code> 來修飾
</summary>
Classes should start as final
, and only be changed to allow subclassing if a valid need for inheritance has been identified. Even in that case, as many definitions as possible within the class should be final
as well, following the same rules.
</details>
<details><summary><i>理由:</i> 組合通常比繼承更合適,選擇使用繼承則很可能意味著在做出決定時需要更多的思考。</summary>
Rationale: Composition is usually preferable to inheritance, and opting in to inheritance hopefully means that more thought will be put into the decision.
</details>
<h3><details><summary>能不寫類型參數的就別寫了</summary>
Omit type parameters where possible
</details></h3>
<details><summary>當對接收者來說一樣時,參數化類型的方法可以省略接收者的類型參數。比如:</summary>
Methods of parameterized types can omit type parameters on the receiving type when they’re identical to the receiver’s. For example:
</details>
struct Composite<T> {
…
func compose(other: Composite<T>) -> Composite<T> {
return Composite<T>(self, other)
}
}
<details><summary>可以改成這樣:</summary>could be rendered as:</details>
struct Composite<T> {
…
func compose(other: Composite) -> Composite {
return Composite(self, other)
}
}
<details><summary><i>理由:</i> 省略多余的類型參數讓意圖更清晰,并且通過對比,讓返回值為不同的類型參數的情況也清楚了很多。</summary>
Rationale: Omitting redundant type parameters clarifies the intent, and makes it obvious by contrast when the returned type takes different type parameters.
</details>
<h3><details><summary>定義操作符 兩邊留空格</summary>
Use whitespace around operator definitions
</details></h3>
<details><summary>當定義操作符時,兩邊留空格。不要醬紫:</summary>
Use whitespace around operators when defining them. Instead of:
</details>
func <|(lhs: Int, rhs: Int) -> Int
func <|<<A>(lhs: A, rhs: A) -> A
<details><summary>應該寫:</summary>write:</details>
func <| (lhs: Int, rhs: Int) -> Int
func <|< <A>(lhs: A, rhs: A) -> A
<details><summary><i>理由:</i> 操作符 由標點字符組成,當立即連著類型或者參數值,會讓代碼非常難讀。加上空格分開他們就清晰了</summary>
Rationale: Operators consist of punctuation characters, which can make them difficult to read when immediately followed by the punctuation for a type or value parameter list. Adding whitespace separates the two more clearly.
</details>