空格/Spacing
Indent using 2 spaces rather than tabs to conserve space and help prevent line wrapping. Be sure to set this preference in Xcode and in the Project settings as shown below:
用两个字符缩进比用制表符(tab)缩进更节省空间,同时能防止过早换行。务必在 Xcode 和项目配置中进行设置,如下所示:
Method braces and other braces (
if
/else
/switch
/while
etc.) always open on the same line as the statement but close on a new line.方法的大括号和其他大括号(
if
else
switch
/while
等)总是在和语句相同的行写左括号,在新行写右括号。Tip: You can re-indent by selecting some code (or Command-A to select all) and then Control-I (or Editor ▸ Structure ▸ Re-Indent in the menu). Some of the Xcode template code will have 4-space tabs hard coded, so this is a good way to fix that.
提示:你可以选中一些代码(或按 Command-A 选中全部)然后按 Control-I(或在目录中选择Editor ▸ Structure ▸ Re-Indent)来重新缩进代码。一些 Xcode 模板代码会使用 4 个空格的制表符硬编码,这就是一个修正它的好方法。
推荐(Preferred):
if user.isHappy {
// Do something
} else {
// Do something else
}
不推荐(Not Preferred):
if user.isHappy
{
// Do something
}
else {
// Do something else
}
There should be one blank line between methods and up to one blank line between type declarations to aid in visual clarity and organization. Whitespace within methods should separate functionality, but having too many sections in a method often means you should refactor into several methods.
方法之间应该有一个空行,类型声明之间最多应该保留一个空行,这样的目的是为了让代码在视觉上更清晰和更有条理。方法中的空白应该按功能分隔代码,但在一个方法中有很多段意味着你应该对其进行重构和封装。
There should be no blank lines after an opening brace or before a closing brace.
在左括号之后或者右括号之前没有独立的空行。
Closing parentheses should not appear on a line by themselves.
右括号不应单独出现在一行中。
推荐(Preferred):
let user = try await getUser(
for: userID,
on: connection)
不推荐(Not Preferred):
let user = try await getUser(
for: userID,
on: connection
)
Colons always have no space on the left and one space on the right. Exceptions are the ternary operator
? :
, empty dictionary[:]
and#selector
syntaxaddTarget(_:action:)
.冒号左边没有空格,右边有空格。三元运算符
? :
、空字典[:]
和#selector
语法里的方法名,例如addTarget(_:action:)
不需要遵守此项规定。
推荐(Preferred):
class TestDatabase: Database {
var data: [String: CGFloat] = ["A": 1.2, "B": 3.2]
}
不推荐(Not Preferred):
class TestDatabase : Database {
var data :[String:CGFloat] = ["A" : 1.2, "B":3.2]
}
Long lines should be wrapped at around 70 characters. A hard limit is intentionally not specified.
当一行的字符数达到 70 个左右时就应该换行,这里并非硬性限制,可自行调整。
Avoid trailing whitespaces at the ends of lines.
避免在行尾增加空格。
Add a single newline character at the end of each file.
在每个文件的结尾增加一个单独的换行符。