• Swift之Swift编码规范


    swift 支持的 markdown 语法。

    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!,对于可选类型Optional多使用as?,?? 可以给变量设置默认值

    // 使用if let as?判断
    if let name = person.name as? String {
    //
    }
    // 给name变量设置默认值
    var name = person.name ?? ""

    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)
    }

     



  • 相关阅读:
    437. Path Sum III
    51. N-Queens
    dfs 感悟
    Topological Sorting
    138 Copy List with Random Pointer
    130. Surrounded Regions
    The sum problem
    A + B Again
    Rectangles
    An easy problem
  • 原文地址:https://www.cnblogs.com/lxlx1798/p/10776016.html
Copyright © 2020-2023  润新知