Fork me on GitHub

Swift 编程规范

代码格式

1.使用空格而不是制表符Tab缩进

不要在工程里使用Tab键,使用空格来进行缩进。在Xcode > Preferences > Text Editing将Tab和自动缩进都设置为4个空格。

2.每行最多80个字符

Xcode > Preferences > Text Editing > Page guide at column:中将最大行长设置为80,过长的一行代码将会导致可读性问题。

3.确保每个文件结尾都有空白行
4.确保每行都不以空白字符作为结尾
1
(Xcode -> Preferences -> Text Editing -> Automatically trim trailing whitespace + Including whitespace-only lines)
5.函数书写

一个典型的Swift函数应该是这样的:

1
2
3
func createDataSource(recid: Int) -> Void {

}

如果一个函数有特别多的参数或者名称很长,应该将其按照参数左对齐分行显示:

1
2
3
4
5
6
func createDataSource(recid: Int,
name: String,
age: Int,
dataSource: Array<Any>) -> Void {

}

函数与函数之间应空一行。

6.字典、数组书写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
let dict: Dictionary<String, Any> = [
"age":17,
"name":"Jack",
"location":"China"
]

let myArray = [1, 2, 3, 4, 5]

let arr: Array<String> = [
"hello",
"world",
"apple",
"iphone"
]
7.当调用的函数有多个参数时,每一个参数另起一行,并比函数名多一个缩进。
1
2
3
4
someFunctionWithManyArguments(
firstArgument: "Hello, I am a string",
secondArgument: resultFromSomeFunction()
thirdArgument: someOtherLocalVariable)
8.当遇到需要处理的数组或字典内容较多需要多行显示时,需把 [ 和 ] 类似于方法体里的括号, 方法体里的闭包也要做类似处理。
1
2
3
4
5
6
7
8
9
10
11
12
13
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)
})
9.应尽量避免出现多行断言,可使用本地变量或其他策略
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 推荐
let firstCondition = x == firstFunction()
let secondCondition = y == secondFunction()
let thirdCondition = z == thirdFunction()
if firstCondition && secondCondition && thirdCondition {
// 你要干什么
}

// 不推荐
if x == firstFunction()
&& y == secondFunction()
&& z == thirdFunction() {
// 你要干什么
}

命名规范

  • 在Swift中不用如Objective-C式 一样添加前缀 (如使用GuybrushThreepwoode而不是LIGuybrushThreepwood)。

  • 用大驼峰命名法(首字母大写)为类型命名 (如 struct, enum, class, typedef, associatedtype 等)。

  • 使用小驼峰命名法 (首字母小写) 为函数,方法,变量,常量,参数等命名。

  • 使用前缀 k + 大驼峰命名法 为所有非单例的静态常量命名。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    class MyClassName {
    // 基元常量使用 k 作为前缀
    static let kSomeConstantHeight: CGFloat = 80.0
    // 非基元常量也是用 k 作为前缀
    static let kDeleteButtonColor = UIColor.redColor()
    // 对于单例不要使用k作为前缀
    static let sharedInstance = MyClassName()
    /* ... */
    }
  • 不要缩写,简写命名,或用单个字母命名。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    // 推荐
    class RoundAnimatingButton: UIButton {
    let animationDuration: NSTimeInterval
    func startAnimating() {
    let firstSubview = subviews.first
    }
    }

    // 不推荐
    class RoundAnimating: UIButton {
    let aniDur: NSTimeInterval
    func srtAnmating() {
    let v = subviews.first
    }
    }
  • 如果原有命名不能明显表明类型,则属性命名内要包括类型信息。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    // 推荐
    class ConnectionTableViewCell: UITableViewCell {
    let personImageView: UIImageView
    let animationDuration: NSTimeInterval
    // 作为属性名的firstName,很明显是字符串类型,所以不用在命名里不用包含String
    let firstName: String
    // 虽然不推荐, 这里用 Controller 代替 ViewController 也可以。
    let popupController: UIViewController
    let popupViewController: UIViewController
    // 如果需要使用UIViewController的子类,如TableViewController, CollectionViewController, SplitViewController, 等,需要在命名里标名类型。
    let popupTableViewController: UITableViewController
    // 当使用outlets时, 确保命名中标注类型。
    @IBOutlet weak var submitButton: UIButton!
    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var nameLabel: UILabel!
    }

    // 不推荐
    class ConnectionTableViewCell: UITableViewCell {
    // 这个不是 UIImage, 不应该以Image 为结尾命名。
    // 建议使用 personImageView
    let personImage: UIImageView
    // 这个不是String,应该命名为 textLabel
    let text: UILabel
    // animation 不能清晰表达出时间间隔
    // 建议使用 animationDuration 或 animationTimeInterval
    let animation: NSTimeInterval
    // transition 不能清晰表达出是String
    // 建议使用 transitionText 或 transitionString
    let transition: String
    // 这个是ViewController,不是View
    let popupView: UIViewController
    // 由于不建议使用缩写,这里建议使用 ViewController替换 VC
    let popupVC: UIViewController
    // 技术上讲这个变量是 UIViewController, 但应该表达出这个变量是TableViewController
    let popupViewController: UITableViewController
    // 为了保持一致性,建议把类型放到变量的结尾,而不是开始,如submitButton
    @IBOutlet weak var btnSubmit: UIButton!
    @IBOutlet weak var buttonSubmit: UIButton!
    // 在使用outlets 时,变量名内应包含类型名。
    // 这里建议使用 firstNameLabel
    @IBOutlet weak var firstName: UILabel!
    }
  • 当给函数参数命名时,要确保函数能理解每个参数的目的。

  • 根据苹果接口设计指导文档, 如果协议描述的是协议做的事应该命名为名词(如Collection) ,如果描述的是行为,需添加后缀 able 或 ing (如Equatable 和 ProgressReporting)。 如果上述两者都不能满足需求,可以添加Protocol作为后缀,例子见下面。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    // 这个协议描述的是协议能做的事,应该命名为名词。
    protocol TableViewSectionProvider {
    func rowHeight(atRow row: Int) -> CGFloat
    var numberOfRows: Int { get }
    /* ... */
    }
    // 这个协议表达的是行为, 以able最为后缀
    protocol Loggable {
    func logCurrentState()
    /* ... */
    }
    // 因为已经定义类InputTextView,如果依然需要定义相关协议,可以添加Protocol作为后缀。
    protocol InputTextViewProtocol {
    func sendTrackingEvent()
    func inputText() -> String
    /* ... */
    }

代码风格

综合

  • 尽可能的多使用let,少使用var。

  • 当需要遍历一个集合并变形成另一个集合时,推荐使用函数 map, filterreduce

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    // 推荐
    let stringOfInts = [1, 2, 3].flatMap { String($0) }
    // ["1", "2", "3"]
    // 不推荐
    var stringOfInts: [String] = []
    for integer in [1, 2, 3] {
    stringOfInts.append(String(integer))
    }
    // 推荐
    let evenNumbers = [4, 8, 15, 16, 23, 42].filter { $0 % 2 == 0 }
    // [4, 8, 16, 42]
    // 不推荐
    var evenNumbers: [Int] = []
    for integer in [4, 8, 15, 16, 23, 42] {
    if integer % 2 == 0 {
    evenNumbers(integer)
    }
    }
  • 如果变量类型可以依靠推断得出,不建议声明变量时指明类型。

  • 如果一个函数有多个返回值,推荐使用 元组 而不是 inout 参数, 如果你见到一个元组多次,建议使用typealias ,而如果返回的元组有三个或多于三个以上的元素,建议使用结构体或类。

    1
    2
    3
    4
    5
    6
    func pirateName() -> (firstName: String, lastName: String) {
    return ("Guybrush", "Threepwood")
    }
    let name = pirateName()
    let firstName = name.firstName
    let lastName = name.lastName
  • 当使用委托和协议时,请注意避免出现循环引用,基本上是在定义属性的时候使用 weak 修饰。

  • 在闭包里使用 self 的时候要注意出现循环引用,使用捕获列表可以避免这一点。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    myFunctionWithClosure() { [weak self] (error) -> Void in
    // 方案 1
    self?.doSomething()
    // 或方案 2
    guard let strongSelf = self else {
    return
    }
    strongSelf.doSomething()
    }
  • Switch 模块中不用显式使用break。

  • 断言流程控制的时候不要使用小括号。

    1
    2
    3
    4
    5
    6
    7
    8
    // 推荐
    if x == y {
    /* ... */
    }
    // 不推荐
    if (x == y) {
    /* ... */
    }
  • 在写枚举类型的时候,尽量简写。

    1
    2
    3
    4
    // 推荐
    imageView.setImageWithURL(url, type: .person)
    // 不推荐
    imageView.setImageWithURL(url, type: AsyncImageView.Type.person)
  • 在使用类方法的时候不用简写,因为类方法不如 枚举 类型一样,可以根据轻易地推导出上下文。

    1
    2
    3
    4
    // 推荐
    imageView.backgroundColor = UIColor.whiteColor()
    // 不推荐
    imageView.backgroundColor = .whiteColor()
  • 不建议使用用self.修饰除非需要。

  • 在新写一个方法的时候,需要衡量这个方法是否将来会被重写,如果不是,请用 final 关键词修饰,这样阻止方法被重写。一般来说,final 方法可以优化编译速度,在合适的时候可以大胆使用它。但需要注意的是,在一个公开发布的代码库中使用 final 和本地项目中使用 final 的影响差别很大的。

Switch语句和枚举

  • 在使用 Switch 语句时,如果选项是有限集合时,不要使用default,相反地,把一些不用的选项放到底部,并用 break 关键词阻止其执行。

  • 因为Swift 中的 switch 选项默认是包含break的, 如果不需要,不用显式的使用 break 关键词。

  • 当定义的选项有关联值时,确保关联值有恰当的名称,而不只是类型。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    // (如 使用 case Hunger(hungerLevel: Int) 而不是 case Hunger(Int))

    enum Problem {
    case attitude
    case hair
    case hunger(hungerLevel: Int)
    }
    func handleProblem(problem: Problem) {
    switch problem {
    case .attitude:
    print("At least I don't have a hair problem.")
    case .hair:
    print("Your barber didn't know when to stop.")
    case .hunger(let hungerLevel):
    print("The hunger level is \(hungerLevel).")
    }
    }
  • 如果default 的选项不应该触发,可以抛出错误 或 断言类似的做法。

    1
    2
    3
    4
    5
    6
    7
    8
    func handleDigit(digit: Int) throws {
    switch digit {
    case 0, 1, 2, 3, 4, 5, 6, 7, 8, 9:
    print("Yes, \(digit) is a digit!")
    default:
    throw Error(message: "The given number was not a digit.")
    }
    }

协议

在实现协议的时候,有两种方式来组织你的代码:

  • 使用 // MARK: 注释来分割协议实现和其他代码。

  • 使用 extension 在 类/结构体已有代码外,但在同一个文件内。

请注意 extension 内的代码不能被子类重写,这也意味着测试很难进行。如果这是经常发生的情况,为了代码一致性最好统一使用第一种办法。否则使用第二种办法,其可以代码分割更清晰。

使用而第二种方法的时候,使用 // MARK: 依然可以让代码在 Xcode 可读性更强。

数组

  1. 基本上不要通过下标直接访问数组内容,如果可能使用如 .first.last, 因为这些方法是非强制类型并不会崩溃。 推荐尽可能使用 for item in items 而不是 for i in 0..

  2. 不要使用 +=+ 操作符给数组添加新元素,使用性能较好的.append().appendContentsOf(),如果需要声明数组基于其他的数组并保持不可变类型,使用 let myNewArray = [arr1, arr2].flatten(),而不是let myNewArray = arr1 + arr2

错误处理

假设一个函数 myFunction 返回类型声明为 String,但是总有可能函数会遇到error,有一种解决方案是返回类型声明为 String?, 当遇到错误的时候返回 nil

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 定义 错误对象 结构体如下:
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
}
}

func readFile(withFilename filename: String) throws -> String {
guard let file = openFile(filename) else {
throw Error(message: “打不开的文件名称 \(filename).")
}
let fileContents = file.read()
file.close()
return fileContents
}
func printSomeFile() {
do {
let fileContents = try readFile(filename)
print(fileContents)
} catch {
print(error)
}
}

其实项目中还是有一些场景更适合声明为可选类型,而不是错误捕捉和处理,比如在获取远端数据过程中遇到错误,nil作为返回结果是合理的,也就是声明返回可选类型比错误处理更合理。

整体上说,如果一个方法有可能失败,并且使用可选类型作为返回类型会导致错误原因湮没,不妨考虑抛出错误而不是吃掉它。

使用guard语句

  • 总体上,我们推荐使用提前返回的策略,而不是 if 语句的嵌套。使用 guard 语句可以改善代码的可读性。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // 推荐
    func eatDoughnut(atIndex index: Int) {
    guard index >= 0 && index < doughnuts else {
    // 如果 index 超出允许范围,提前返回。
    return
    }
    let doughnut = doughnuts[index]
    eat(doughnut)
    }
    // 不推荐
    func eatDoughnuts(atIndex index: Int) {
    if index >= 0 && index < donuts.count {
    let doughnut = doughnuts[index]
    eat(doughnut)
    }
    }
  • 在解析可选类型时,推荐使用guard语句,而不是if语句,因为guard语句可以减少不必要的嵌套缩进。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    // 推荐
    guard let monkeyIsland = monkeyIsland else {
    return
    }
    bookVacation(onIsland: monkeyIsland)
    bragAboutVacation(onIsland: monkeyIsland)

    // 不推荐
    if let monkeyIsland = monkeyIsland {
    bookVacation(onIsland: monkeyIsland)
    bragAboutVacation(onIsland: monkeyIsland)
    }

    // 禁止
    if monkeyIsland == nil {
    return
    }
    bookVacation(onIsland: monkeyIsland!)
    bragAboutVacation(onIsland: monkeyIsland!)
  • 当解析可选类型需要决定在if语句和guard语句之间做选择时,最重要的判断标准是是否让代码可读性更强,实际项目中会面临更多的情景,如依赖 2 个不同的布尔值,复杂的逻辑语句会涉及多次比较等,大体上说,根据你的判断力让代码保持一致性和更强可读性, 如果你不确定if语句和guard语句哪一个可读性更强,建议使用guard

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    // if 语句更有可读性
    if operationFailed {
    return
    }
    // guard 语句这里有更好的可读性
    guard isSuccessful else {
    return
    }
    // 双重否定不易被理解 - 不要这么做
    guard !operationFailed else {
    return
    }
  • 如果需要在2个状态间做出选择,建议使用if语句,而不是使用guard语句。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    // 推荐
    if isFriendly {
    print("你好, 远路来的朋友!")
    } else {
    print(“穷小子,哪儿来的?")
    }
    // 不推荐
    guard isFriendly else {
    print("穷小子,哪儿来的?")
    return
    }
    print("你好, 远路来的朋友!")
  • 你只应该在在失败情形下退出当前上下文的场景下使用guard语句,下面的例子可以解释if语句有时候比guard语句更合适 – 我们有两个不相关的条件,不应该相互阻塞。

    1
    2
    3
    4
    5
    6
    if let monkeyIsland = monkeyIsland {
    bookVacation(onIsland: monkeyIsland)
    }
    if let woodchuck = woodchuck where canChuckWood(woodchuck) {
    woodchuck.chuckWood()
    }
  • 我们会经常遇到使用guard语句拆包多个可选值,如果所有拆包失败的错误处理都一致可以把拆包组合到一起 (如 return,break, continue,throw 等).

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // 组合在一起因为可能立即返回
    guard let thingOne = thingOne,
    let thingTwo = thingTwo,
    let thingThree = thingThree else {
    return
    }
    // 使用独立的语句 因为每个场景返回不同的错误
    guard let thingOne = thingOne else {
    throw Error(message: "Unwrapping thingOne failed.")
    }
    guard let thingTwo = thingTwo else {
    throw Error(message: "Unwrapping thingTwo failed.")
    }
    guard let thingThree = thingThree else {
    throw Error(message: "Unwrapping thingThree failed.")
    }

写在最后

本文内容是从网络上搜集并结合个人编程经验总结,下面是参考链接。

参考链接

-------------本文结束感谢您的阅读-------------

本文作者:乔羽 / FightingJoey

发布时间:2017年07月19日 - 09:55

最后更新:2018年09月27日 - 10:10

原始链接:https://fightingjoey.github.io/2017/07/19/开发/Swift-编程规范/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!