Swift 4.0 編碼規範,持續更新中...
自Swift 3.0 以來,語言已經比較成熟,用Swift語言來開發iOS App 的開發者越來越多,那麼一份權威而全面的規範就很有必要了。蘋果官方的文件有時間大家還是多看看,筆者參考官方文件和各路大神的經驗,寫下了一份基於Swift 4.0 的編碼規範,並會持續更新,歡迎大家補充指正。
1. 編碼格式
1.1 使用二元運算子(+, -,==, 或->)的前後都需要新增空格
let value = 1 + 2
1.2 在逗號後面加一個空格
let titleArray = [1, 2, 3, 4, 5]
1.3 方法的左大括號不要另起,並和方法名之間留有空格,註釋空格
// function Define
func myFunction {
// 處理
}
1.4 判斷語句不用加括號
if typeValue == 1 {
// 處理
}
1.5 儘量不使用self. 除非方法引數與屬性同名
func setPerson(name: String, pAge: Int) {
self.name = name
age = pAge
}
1.6 在訪問列舉型別時,使用更簡潔的點語法
enum Direction {
case north
case south
case east
case west
}
let currentDirection = .west
1.7 新增有必要的註釋,儘可能使用Xcode註釋快捷鍵(⌘⌥/)
/// <#Description#>
///
/// - Parameters:
/// - tableView: <#tableView description#>
/// - section: <#section description#>
/// - Returns: <#return value description#>
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataList.count
}
1.8 使用 // MARK: -,按功能、協議、代理等分組
// MARK: - UITableViewDelegate
// MARK: - Action
// MARK: - Request
1.9 協議一致性:當物件要實現協議一致性時,推薦使用 extension 隔離協議中的方法集,這樣讓相關方法和協議集中在一起,方便歸類和查詢
// MARK: - UICollectionViewDelegate, UICollectionViewDataSource
extension XMHomeViewController: UICollectionViewDelegate, UICollectionViewDataSource {
// 代理方法
}
// MARK: - HttpsRequest
extension XMHomeViewController {
// 網路請求方法
}
1.10 當對外介面不相容時,使用@available(iOS x.0, *) 標明介面適配的起始系統版本號
@available(iOS 8.0, *)
func myFunction() {
//
}
2. 命名規範
2.1 常量,變數,函式,方法的命名規則使用小駝峰規則,首字母小寫,型別名使用大駝峰規則,首字母大寫。
class MyClass: class {
let myImageView: UIImageView
let myName: String
}
2.2 當命名裡出現縮寫詞時,縮寫詞要麼全部大寫,要麼全部小寫,以首字母大小寫為準
let htmlString = "https://www.baidu.com"
let urlString: URLString
let userID: UserID
class HTMLModel {
//
}
2.3 bool型別命名時,使用is作為字首
var isMine: Bool = false
2.4 Swift中類別(類,結構體)在編譯時會把模組設定為預設的名稱空間,所以不用為了區分類別而新增字首,比如XYHomeViewController,但是為了和引用的第三方庫作區分,建議可以繼續使用字首,以作為規範化處理,結構更清晰。
2.5 懶載入用來細緻地控制物件的生命週期,這對於想實現延遲載入檢視的UIViewController特別有用
// MARK: - 懶載入
private lazy var tableView: UITableView = {
let tableView = UITableView.init(frame: CGRect.zero, style: .plain)
tableView.separatorStyle = .none
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 200
tableView.dataSource = self
tableView.delegate = self
tableView.register(UINib(nibName: homeListCell, bundle: nil), forCellReuseIdentifier: homeListCell)
return tableView
}()
2.6 當函式的第一個引數構成整個語句的介詞時(如,at, by, for, in, to, with 等),為第一個引數新增介詞引數標籤
func login(with username: String?, password: String?) {
//
}
3. 語法規範
3.1 可選型別拆包取值時,使用if let 判斷
if let data = result.data {
//
}
3.2 多個可選型別拆包取值時,將多個if let 判斷合併
if let name = person.name, let age = person.age {
//
}
3.3 儘量不要使用 as! 或 try!
// 使用if let as?判斷
if let name = person.name as? String {
//
}
3.4 陣列和字典變數定義時需要標明泛型型別,並使用更簡潔清晰的語法
var names: [String] = []
var values: [String: Int] = [:]
var person: [String: Any] = [:]
3.5 常量定義,建議儘可能定義在型別裡面,避免汙染全域性名稱空間,如果是其他地方有可能複用的cell可以定義在型別外面
static let homeListCell = "HomeListCell"
class HomeListCell: UITableViewCell {
static let kHomeCellHeight = 80.0
//
}
3.6 當方法最後一個引數是Closure型別,呼叫時建議使用尾隨閉包語法
UIView.animateWithDuration(1.0) {
self.myView.alpha=0
}
3.8 最短路徑規則:當編碼遇到條件判斷時,左邊的距離是黃金路徑或幸福路徑,因為路徑越短,速度越快。guard 就為此而生的。
func login(with username: String?, password: String?) throws -> LoginError {
guard let username = username else {
throw .noUsername
}
guard let password = password else {
throw .noPassword
}
// 處理登入
}
3.9 迴圈遍歷使用for-in表示式
// 迴圈
for _ in 0..<list.count {
print("items")
}
// 遍歷
for(index, person) in personList.enumerate() {
print("\(person)is at position #\(index)")
}
// 間隔2位迴圈
for index in 0.stride(from: 0, to: items.count, by: 2) {
print(index)
}
// 翻轉
for index in (0...3).reverse() {
print(index)
}