Xcode设置:Xcode > Preferences > Text Editing > Indentation
2. 单行长度
避免一行代码超过160 个字符
Xcode设置:Xcode > Preferences > Text Editing > Page Guide Column
3. 删除行尾空格
启用自动删除行尾空格
Xcode设置:Xcode > Preferences > Text Editing > Automatically trim trailing whitespace & Including whitespace-only lines
4. 左括号放在代码后面
禁止左括号单独一行
classMyClass {funcmyMethod() {if x == y {/* ... */ } elseif x == z {/* ... */ } else {/* ... */ } }/* ... */}
5. 冒号前不需要空格
在属性,常量,变量,字典的key , 函数参数,协议, 类等类型编写时,不要在冒号前加空格
// 属性类型let aProperty: MyPropertyClass// 字典let aDictionary: [String:Int] = ["key1":2,"key2":3]// 函数funcaFunction<T, U:SomeProtocol>(argA: U, argB: T) where T.RelatedType == U {/* ... */}// 函数调用myFunction(argument:"MyArgument")// classclassDog:Wolf {/* ... */}// 协议extensionPirateViewController:UITableViewDataSource {/* ... */}
6. 逗号后面需要空格
在数组元素, 条件语句等逗号后面需要增加空格
// 数组let anArray = ["a", "b", "c"]// 条件语句if a == b, b == c {/* ... */}
7. 操作符前后需要空格
在操作符 (+, -, ==, > ...) 前后都需要有一个空格,
(之前需要有一个空格,)之后需要有一个空格
let myValue =20+ (30/2) *3if1+1==3 {/* ... */}
8. 多行缩进
当一个函数或if语句跨多行时,使用Xcode的推荐规则进行缩进
// 当一个函数跨行时,使用 Xcode 缩进规则缩进funcmyFunction(parameterOne: String,parameterTwo: String,parameterThree: String) {// Xcode indents to here for this kind of statementprint("\(parameterOne)\(parameterTwo)\(parameterThree)")}// if 语句跨行时,使用 Xcode 缩进规则缩进 逻辑运算符换行放在行首if myFirstValue >(mySecondValue + myThirdValue)&& mySecondValue == myThirdValue&& myThirdValue == (mySecondValue - myFirstValue) {// Xcode indents to here for this kind of statementprint("Hello, World!")}
9. 多个参数的函数调用
当调用一个多个参数的函数或者一行很长时,把每个参数放在单独一行
myAwesomeFunctionWithLotsOfArgs( firstArgument:"Hello, I am a string", secondArgument:"Test", thirdArgument:2)
someFunctionWithABunchOfArguments( someStringArgument:"hello I am a string", someArrayArgument: ["dadada daaaa daaaa dadada daaaa daaaa dadada daaaa daaaa","string one is crazy - what is it thinking?" ], someDictionaryArgument: ["dictionary key 1":"some value 1, but also some more text here","dictionary key 2":"some value 2" ], someClosure: { parameter1 in print(parameter1) })
let firstCondition = x ==firstReallyReallyLongPredicateFunction()let secondCondition = y ==secondReallyReallyLongPredicateFunction()let thirdCondition = z ==thirdReallyReallyLongPredicateFunction()if firstCondition && secondCondition && thirdCondition {// do something}
替换下面的代码👇
if x ==firstReallyReallyLongPredicateFunction()&& y ==secondReallyReallyLongPredicateFunction()&& z ==thirdReallyReallyLongPredicateFunction() {// do something}
13. 控制流语句避免使用括号
在Swift标准中,不需要在控制流语句中使用括号
// ✅推荐if x == y {/* ... */}// ❌不推荐if(x == y) {/* ... */}