前言
關于Swift的代碼的相關規(guī)范,不同的開發(fā)者都有自己相應的規(guī)范,可能還是很多人根本就沒有規(guī)范。為了保證同一個公司同一個項目組中代碼美觀并且一致,這里寫下這份Swift編程規(guī)范指南。該指南首要目標是讓代碼緊湊,可讀性更高且簡潔。
代碼格式
使用四個空格進行縮進
每行最多160個字符,這樣可以避免一行過長(Xcode->Preferences->Text Editing->Page guide at column: 設置成160即可)
確保每個文件結尾都有空白行
確保每行都不以空白符作為結尾(Xcode->Preferences->Text Editing->Automatically trim trailing whitespace + Including whitespace-only lines)
左大括號不用另起一行
class SomeClass {
func someMethod() {
if x == y {
/* ... */
} else if x == z {
/* ... */
} else {
/* ... */
}
}
/* ... */
}
要在逗號后面加空格
let array = [1, 2, 3, 4, 5];
二元運算符(+,==,或>)的前后都需要添加空格,左小括號和右小括號前面不需要空格。
let value = 20 + (34 / 2) * 3
if 1 + 1 == 2 {
//TODO
}
func pancake -> Pancake {
/** do something **/
}
遵守Xcode內置的縮進格式,當聲明的一個函數(shù)需要跨多行時,推薦使用Xcode默認格式。
// Xcode針對跨多行函數(shù)聲明縮進
func myFunctionWithManyParameters(parameterOne: String,
parameterTwo: String,
parameterThree: String) {
// Xcode會自動縮進
print("\(parameterOne) \(parameterTwo) \(parameterThree)")
}
// Xcode針對多行 if 語句的縮進
if myFirstVariable > (mySecondVariable + myThirdVariable)
&& myFourthVariable == .SomeEnumValue {
// Xcode會自動縮進
print("Hello, World!")
}
當調用一個函數(shù)有多個參數(shù)時,每個參數(shù)另起一行,比函數(shù)名多一個縮進。
functionWithArguments(
firstArgument: "Hello, I am a string",
secondArgument: resultFromSomeFunction()
thirdArgument: someOtherLocalVariable)
當遇到需要處理的數(shù)組或字典內容較多需要多行顯示時,需要把[和]類似方法體里面的括號,方法體里的閉合也要做類似的處理。
functionWithBunchOfArguments(
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)
})
盡量避免出現(xiàn)多行斷言,可使用本地變量或其他策略
// 推薦
let firstCondition = x == firstReallyReallyLongPredicateFunction()
let secondCondition = y == secondReallyReallyLongPredicateFunction()
let thirdCondition = z == thirdReallyReallyLongPredicateFunction()
if firstCondition && secondCondition && thirdCondition {
// 你要干什么
}
// 不推薦
if x == firstReallyReallyLongPredicateFunction()
&& y == secondReallyReallyLongPredicateFunction()
&& z == thirdReallyReallyLongPredicateFunction() {
// 你要干什么
}
命名
使用帕斯卡拼寫法(又名大駱駝拼寫法,首字母大寫)為類型命名(如struct,enum,class,typedef,associatedtype等)。
使用小駱駝拼寫法(首字母小寫)為函數(shù),方法,常亮,參數(shù)等命名。
首字母縮略詞在命名中一般來說都是全部大寫,例外的情形是如果首字母縮略詞是一個命名的開始部分,而這個命名需要小寫字母作為開頭,這種情形下首字母縮略詞全部小寫。
// "HTML" 是變量名的開頭, 需要全部小寫 "html"
let htmlBodyContent: String = "<p>Hello, World!</p>"
// 推薦使用 ID 而不是 Id
let profileID: Int = 1
// 推薦使用 URLFinder 而不是 UrlFinder
class URLFinder {
/* ... */
}
使用前綴 k + 大駱駝命名法 為所有非單例的靜態(tài)常量命名。
class ClassName {
// 基元常量使用 k 作為前綴
static let kSomeConstantHeight: CGFloat = 80.0
// 非基元常量也是用 k 作為前綴
static let kDeleteButtonColor = UIColor.redColor()
// 對于單例不要使用k作為前綴
static let sharedInstance = MyClassName()
/* ... */
}
命名應該具有描述性個清晰性的。
// 推薦
class RoundAnimatingButton: UIButton { /* ... */ }
// 不推薦
class CustomButton: UIButton { /* ... */ }
不要縮寫、簡寫或單個字母命名。
// 推薦
class RoundAnimatingButton: UIButton {
let animationDuration: NSTimeInterval
func startAnimating() {
let firstSubview = subviews.first
}
}
// 不推薦
class RoundAnimating: UIButton {
let aniDur: NSTimeInterval
func srtAnmating() {
let v = subviews.first
}
}
如果原有命名不能明顯表明類型,則屬性命名內要包括類型信息。
// 推薦
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!
}
當給函數(shù)參數(shù)命名時,要確保函數(shù)能夠理解每個參數(shù)的目的。
代碼風格
綜合
盡可能多使用let,少使用var。
當需要遍歷一個集合變形成另一個集合時,推薦使用函數(shù)flatMap,filter,和reduce。
// 推薦
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)
}
}
如果變量類型可以依靠判斷得出,不建議聲明變量時指明類型。
如果一個函數(shù)有多個返回值,推薦使用 元組 而不是inout參數(shù),如果這個元組在多個地方都會使用,建議使用typealias來定義這個元組,而如果返回的元組有三個或者三個以上的元素,建議使用結構體或類。
func pirateName() -> (firstName: String, lastName: String) {
return ("Guybrush", "Threepwood")
}
let name = pirateName()
let firstName = name.firstName
let lastName = name.lastName
當使用委托和協(xié)議時,請注意避免出現(xiàn)循環(huán)引用,基本上是在定義屬性的時候使用weak修飾。
在閉包里使用self的時候需要注意避免出現(xiàn)循環(huán)引用,使用捕獲列表可以避免這一點。
functionWithClosure() { [weak self] (error) -> Void in
// 方案 1
self?.doSomething()
// 或方案 2
guard let strongSelf = self else {
return
}
strongSelf.doSomething()
}
switch 模塊中不用顯式使用break。
斷言流程控制的時候不要使用小括號。
// 推薦
if x == y {
/* ... */
}
// 不推薦
if (x == y) {
/* ... */
}
在寫枚舉類型的時候,盡量簡寫。
// 推薦
imageView.setImageWithURL(url, type: .person)
// 不推薦
imageView.setImageWithURL(url, type: AsyncImageView.Type.person)
在使用類方法的時候不用簡寫,因為類方法和枚舉類型不一樣,不能輕易地推導出上下文。
// 推薦
imageView.backgroundColor = UIColor.whiteColor()
// 不推薦
imageView.backgroundColor = .whiteColor()
不建議使用self,除非必須得要。
在寫一個方法的時候,需要衡量這個方法將來是否會被重寫,如果不是請用final關鍵字修飾,這樣組織方法被重寫。一般來說final修飾符可以優(yōu)化編譯速度,在合適的時候大膽的使用它吧。需要注意的是,在一個公開發(fā)布的代碼庫中使用final和在本地項目中使用final的影響差別很大。
在使用一些語句如else,catch等緊隨代碼塊關鍵字的時候,確保代碼塊和關鍵字在同一行。
if someBoolean {
// 你想要什么
} else {
// 你不想做什么
}
do {
let fileContents = try readFile("filename.txt")
} catch {
print(error)
}
訪問控制修飾符
如果需要把訪問修飾符放到第一個位置。
// 推薦
private static let kMyPrivateNumber: Int
// 不推薦
static private let kMyPrivateNumber: Int
訪問修飾符不應該單獨另起一行,應和訪問修飾符描述的對象保持在同一行。
// 推薦
public class Pirate {
/* ... */
}
// 不推薦
public
class Pirate {
/* ... */
}
默認的訪問修飾符是internal,可省略不寫。
當一個變量需要被單元測試 訪問時,需要聲明為 internal 類型來使用@testable import {ModuleName}。 如果一個變量實際上是private 類型,而因為單元測試需要被聲明為 internal 類型,確定添加合適的注釋文檔來解釋為什么這么做。這里添加注釋推薦使用 - warning: 標記語法。
/**
這個變量是private 名字
- warning: 定義為 internal 而不是 private 為了 `@testable`.
*/
let pirateName = "LeChuck"
自定義操作符
不推薦使用自定義操作符,如果需要創(chuàng)建函數(shù)代替。
在重寫操作符之前,請慎重考慮是否有充分的理由一定要在全局范圍內創(chuàng)建新的操作符,而不是使用其他策略。
你可以重載現(xiàn)有的操作符來支持新的類型(特別是==),但是新定義的必須保留操作符原來的含義,比如==必須用來測試是否相等并返回布爾值。
switch語句和枚舉
使用swift語句時,如果選項是有限集合時,不要使用default,相反的,把一些不用的選項放到底部,并用break關鍵詞阻止其執(zhí)行。
應為swift中的switch選項默認是包含break的,所以不需要使用break關鍵字。
case 語句 應和 switch 語句左對齊,并在 標準的 default 上面。
當定義的選項有關聯(lián)值時,確保關聯(lián)值有恰當?shù)拿Q,而不只是類型。
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).")
}
}
推薦盡可能使用fall through。
如果default 的選項不應該觸發(fā),可以拋出錯誤 或 斷言類似的做法。
func handleDigit(digit: Int) throws {
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.")
}
可選類型
唯一使用隱式拆包可選型的場景是結合@IBOutlets,在其他場景使用非可選類型和常規(guī)可選類型,即使有的場景你確定有的變量使用的時候永遠不會為nil,但這樣做可以保持一致性和程序更加健壯。
不要使用as!和try!,除非萬不得已。
如果對于一個變量你不打算聲明為可選類型,但當需要檢查變量值是否為nil,推薦使用當前值和nil直接比較,而不推薦使用if let的語法。并且nil在前變量在后。
// 推薦
if nil != someOptional {
// 你要做什么
}
// 不推薦
if let _ = someOptional {
// 你要做什么
}
不要使用unowned,unowned和weak修飾變量基本上等價,并且都是隱式拆包(unowned在引用計數(shù)上有少許性能優(yōu)化),由于不推薦使用隱式拆包,也不推薦使用unowned變量。
// 推薦
weak var parentViewController: UIViewController?
// 不推薦
weak var parentViewController: UIViewController!
unowned var parentViewController: UIViewController
guard let myVariable = myVariable else {
return
}
協(xié)議
在實現(xiàn)協(xié)議的時候,有兩種方式來組織你的代碼:
使用//MAKR:注釋來實現(xiàn)分割協(xié)議和其他代碼。
使用 extension 在 類/結構體已有代碼外,但在同一個文件內。
請注意 extension 內的代碼不能被子類重寫,這也意味著測試很難進行。 如果這是經(jīng)常發(fā)生的情況,為了代碼一致性最好統(tǒng)一使用第一種辦法。否則使用第二種辦法,其可以代碼分割更清晰。使用而第二種方法的時候,使用 // MARK: 依然可以讓代碼在 Xcode 可讀性更強。
屬性
對于只讀屬性,提供getter而不是get{}。
var computedProperty: String {
if someBool {
return "I'm a mighty pirate!"
}
return "I'm selling these fine leather jackets."
}
對于屬性相關方法 get {}, set {}, willSet, 和 didSet, 確保縮進相關代碼塊。
對于willSet/didSet 和 set 中的舊值和新值雖然可以自定義名稱,但推薦使用默認標準名稱 newValue/oldValue。
var computedProperty: String {
get {
if someBool {
return "I'm a mighty pirate!"
}
return "I'm selling these fine leather jackets."
}
set {
computedProperty = newValue
}
willSet {
print("will set to \(newValue)")
}
didSet {
print("did set from \(oldValue) to \(newValue)")
}
}
在創(chuàng)建常量的時候,使用static關鍵字修飾。
class MyTableViewCell: UITableViewCell {
static let kReuseIdentifier = String(MyTableViewCell)
static let kCellHeight: CGFloat = 80.0
}
聲明單例屬性可以通過下面方式進行:
class PirateManager {
static let sharedInstance = PirateManager()
/* ... */
}
閉包
如果參數(shù)的類型很明顯,可以在函數(shù)名里可以省略參數(shù)類型, 但明確聲明類型也是允許的。 代碼的可讀性有時候是添加詳細的信息,而有時候部分重復,根據(jù)你的判斷力做出選擇吧,但前后要保持一致性。
// 省略類型
doSomethingWithClosure() { response in
print(response)
}
// 明確指出類型
doSomethingWithClosure() { response: NSURLResponse in
print(response)
}
// map 語句使用簡寫
[1, 2, 3].flatMap { String($0) }
如果使用捕捉列表 或 有具體的非 Void返回類型,參數(shù)列表應該在小括號內, 否則小括號可以省略。
// 因為使用捕捉列表,小括號不能省略。
doSomethingWithClosure() { [weak self] (response: NSURLResponse) in
self?.handleResponse(response)
}
// 因為返回類型,小括號不能省略。
doSomethingWithClosure() { (response: NSURLResponse) -> String in
return String(response)
}
如果閉包是變量類型,不需把變量值放在括號中,除非需要,如變量類型是可選類型(Optional?), 或當前閉包在另一個閉包內。確保閉包里的所以參數(shù)放在小括號中,這樣()表示沒有參數(shù),Void 表示不需要返回值。
let completionBlock: (success: Bool) -> Void = {
print("Success? \(success)")
}
let completionBlock: () -> Void = {
print("Completed!")
}
let completionBlock: (() -> Void)? = nil
數(shù)組
基本上不要通過下標直接訪問數(shù)組內容,如果可能使用.first或.last,因為這些方法是非強制類型并不會奔潰。推薦盡可能使用 for item in items 而不是 for i in 0..n。
不是使用+=或+操作符給數(shù)組添加新元素,使用性能較好的.append()或appendContentsOf(),如果需要聲明數(shù)組基于其他數(shù)組并保持不可變類型,使用let myNewArray = [arr1, arr2].flatten(),而不是let myNewArray = arr1 + arr2 。
錯誤處理
假設一個函數(shù) myFunction 返回類型聲明為 String,但是總有可能函數(shù)會遇到error,有一種解決方案是返回類型聲明為 String?, 當遇到錯誤的時候返回 nil。
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 。
定義 錯誤對象 結構體如下:
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)
}
}
其實項目中還是有一些場景更適合聲明為可選類型,而不是錯誤捕捉和處理,比如在獲取遠端數(shù)據(jù)過程中遇到錯誤,nil作為返回結果是合理的,也就是聲明返回可選類型比錯誤處理更合理。
整體上說,如果一個方法有可能失敗,并且使用可選類型作為返回類型會導致錯誤原因湮沒,不妨考慮拋出錯誤而不是吃掉它。
使用 guard 語句
總體上,我們推薦使用提前返回的策略,而不是 if 語句的嵌套。使用 guard 語句可以改善代碼的可讀性。
// 推薦
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 語句可以減少不必要的嵌套縮進。
// 推薦
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 個不同的布爾值,復雜的邏輯語句會涉及多次比較等,大體上說,根據(jù)你的判斷力讓代碼保持一致性和更強可讀性, 如果你不確定 if 語句 和 guard 語句哪一個可讀性更強,建議使用 guard 。
// if 語句更有可讀性
if operationFailed {
return
}
// guard 語句這里有更好的可讀性
guard isSuccessful else {
return
}
// 雙重否定不易被理解 - 不要這么做
guard !operationFailed else {
return
}
如果需要在2個狀態(tài)間做出選擇,建議使用if 語句,而不是使用 guard 語句。
// 推薦
if isFriendly {
print("你好, 遠路來的朋友!")
} else {
print(“窮小子,哪兒來的?")
}
// 不推薦
guard isFriendly else {
print("窮小子,哪兒來的?")
return
}
print("你好, 遠路來的朋友!")
你只應該在在失敗情形下退出當前上下文的場景下使用 guard 語句,下面的例子可以解釋 if 語句有時候比 guard 語句更合適 – 我們有兩個不相關的條件,不應該相互阻塞。
if let monkeyIsland = monkeyIsland {
bookVacation(onIsland: monkeyIsland)
}
if let woodchuck = woodchuck where canChuckWood(woodchuck) {
woodchuck.chuckWood()
}
我們會經(jīng)常遇到使用 guard 語句拆包多個可選值,如果所有拆包失敗的錯誤處理都一致可以把拆包組合到一起 (如 return, break, continue,throw 等)。
// 組合在一起因為可能立即返回
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.")
}
文檔/注釋
文檔
如果一個函數(shù)比 O(1) 復雜度高,你需要考慮為函數(shù)添加注釋,因為函數(shù)簽名(方法名和參數(shù)列表) 并不是那么的一目了然,這里推薦比較流行的插件 VVDocumenter. 不論出于何種原因,如果有任何奇淫巧計不易理解的代碼,都需要添加注釋,對于復雜的 類/結構體/枚舉/協(xié)議/屬性 都需要添加注釋。所有公開的 函數(shù)/類/變量/枚舉/協(xié)議/屬性/常數(shù) 也都需要添加文檔,特別是 函數(shù)聲明(包括名稱和參數(shù)列表) 不是那么清晰的時候。
在注釋文檔完成后,你應檢查格式是否正確。
注釋文檔規(guī)則如下:
一行不要超過160個字符 (和代碼長度限制雷同)。
即使文檔注釋只有一行,也要使用模塊化格式 (/* /)。
注釋模塊中的空行不要使用 * 來占位。
確定使用新的 – parameter 格式,而不是就得 Use the new -:param: 格式,另外注意 parameter 是小寫的。
如果需要給一個方法的 參數(shù)/返回值/拋出異常 添加注釋,務必給所有的添加注釋,即使會看起來有部分重復,否則注釋會看起來不完整,有時候如果只有一個參數(shù)值得添加注釋,可以在方法注釋里重點描述。
對于負責的類,在描述類的使用方法時可以添加一些合適的例子,請注意Swift注釋是支持 MarkDown 語法的。
/**
## 功能列表
這個類提供下一下很贊的功能,如下:
- 功能 1
- 功能 2
- 功能 3
## 例子
這是一個代碼塊使用四個空格作為縮進的例子。
let myAwesomeThing = MyAwesomeClass()
myAwesomeThing.makeMoney()
## 警告
使用的時候總注意以下幾點
1. 第一點
2. 第二點
3. 第三點
*/
class MyAwesomeClass {
/* ... */
}
在寫文檔注釋時,盡量保持簡潔。
其他注釋原則
// 后面要保留空格。
注釋必須要另起一行。
使用注釋 // MARK: - xoxo 時, 下面一行保留為空行。
class Pirate {
// MARK: - 實例屬性
private let pirateName: String
// MARK: - 初始化
init() {
/* ... */
}
}
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對html5模板網(wǎng)的支持。