美文网首页
Swift 代码规范总结更新

Swift 代码规范总结更新

作者: ClementGu | 来源:发表于2020-03-31 20:14 被阅读0次

    1.所有继承的冒号: 后面需要留一个空格

    return UIColor(red: 0.06, green: 0.09, blue: 0.13, alpha: 0.15)
    

    2.let 、var 等声明之间空格只能有一个

    var table: UITableView?
    

    3.创建控件方法需要封装,或者懒加载不要直接写在上面

      class func dz_borderBtn_5(title: String,fontSize: CGFloat = 10) -> UIButton
        {
            let name = UIButton(type: .custom)
            name.setTitle(title, for: .normal)
            name.setTitleColor(.dz_defaultColor, for: .normal)
            name.layer.borderWidth = 0.5
            name.layer.borderColor = UIColor.dz_borderColor_ACAEB1.cgColor
            name.titleLabel?.font = .dz_Chinese(name: .regular, size: fontSize)
            return name
        }
    

    4.当方法过长时以参数为单位换行,便于阅读与维护。

    let constraint = NSLayoutConstraint(
                item: self,
                attribute: .height,
                relatedBy: .equal,
                toItem: nil,
                attribute: .notAnAttribute,
                multiplier: 1,
                constant: 67)
    

    5.所有继承逗号之间也要留空格

    class DZSecondaryTableAdapter: NSObject, UITableViewDelegate, UITableViewDataSource
    

    6 系统可以自动推断出来的直接用.点语法不需要前缀这样会提高其查找性能

    name.setTitleColor( .dz_defaultColor, for: .normal)
    

    7.类后面的括号要留一个空格

    extension UILabel {
    

    8.尽量少用强制拆包

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! DZDocumentInfoTableCell
    if let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? DZDocumentInfoTableCell {
    }
    

    9.去除所有因为init方便提示写的init方法

    UILabel.init(frame: <#T##CGRect#>) //错误
    UILabel(frame: <#T##CGRect#>)  //正确
    

    10.将方法分类并且贴上标签,待完成及bug修改也需要写上相应标签来提示


    image.png

    11.枚举 驼峰命名 case的首字母大写

    enum Shape {
      case Rectangle
      case Square
      case Triangle
      case Circle
    }
    

    12 注释,教程 对方法功能等使用进行描述。

      //当你调用方法时确保时间参数传递格式为“yyyy/mm/dd”
      func dateFromString(dateString: String) -> NSDate
      {
          //...
      }
    

    13 缩进 tab的缩进默认时4个空格,可以修改成2个空格来节省空空间,防止换行。
    Xcode -> Preferences -> Text Editing -> indentation -> tab Width 和 Indent Width 修改成2行

    image.png

    14 全局缩进 cmd + A 全局选中(或者鼠标圈中) -> Control + I (整体缩进对齐)

    1. 方法间隔 每个方法之间需要空格一行 保证视觉清晰。
    2. 注释不要写在代码内,不利于注释生成文档。保证注释碎方法变动而更新,或者删除。
    3. 三目运算,使用时要考虑到代码的可读性,或者用if/else 代替让代码易读易懂。
    prefered:
    let anInt = boolValue ? 1 : 2
      let anotherInt: Int
    best:
      if boolValue {
          anotherInt = 1
      } else {
          anotherInt = 2
      }
    }
    not prefered:
    let result = a > b ? c > d ? c : d : e
    

    18 结构体和
    类是引用类型,结构体是值类型,也就是说,相同的两个数组[a,b,c]他们是对等的完全可以替换的可以认为是同一个。一个Person 类即使属性都完全一样也是代表两个人,有自己的id和生命周期。

    19.定义

    • 隐式拆包定义属性 x: Int 冒号前面不空格后面空格
    • 多个变量用途类型相同,可以定义在同一行
    • get set 要缩进
    • 不要重复设置修饰符(类似internal)如果默认就是这种类型的话,包括重写。这边有疑问,我了解的是在类型前写修饰符能提高效率,因为系统不需要进行判断来定义了。(有时间具体研究了更新,可以先不写,因为大部分都不写)
      class Circle: Shape {
      var x: Int, y: Int
      var radius: Double
      var diameter: Double {
        get {
          return radius * 2
        }
        set {
          radius = newValue / 2
        }
      }
    
      init(x: Int, y: Int, radius: Double) {
        self.x = x
        self.y = y
        self.radius = radius
      }
    
      convenience init(x: Int, y: Int, diameter: Double) {
        self.init(x: x, y: y, radius: diameter / 2)
      }
    
      func describe() -> String {
        return "I am a circle at \(centerString()) with an area of \(computeArea())"
      }
    
      override func computeArea() -> Double {
        return M_PI * radius * radius
      }
    
      private func centerString() -> String {
        return "(\(x),\(y))"
      }
    }
    

    20 self 的使用 遵循swift的简介宗旨,self是不用的,除了几个特定情况

    • 构造函数或者方法中的参数跟定义的属性一样时,用self来表示类的属性以区别参数。
    • 闭包中使用,这是编译器要求的。
      class BoardLocation {
      let row: Int, column: Int
    
      init(row: Int, column: Int) {
        self.row = row
        self.column = column
        
        let closure = {
          println(self.row)
        }
      }
    }
    
    1. 协议实现 在累的扩展中实现,简单清晰集中。
    2. 方法要简洁,把左边的大括号跟方法写在同一行,如果方法太长那么,找个合适的地方换行,并且第二行缩进。
    func reticulateSplines(spline: [Double], adjustmentFactor: Double,
        translateConstant: Int, comment: String) -> Bool {
      // reticulate code goes here
    }
    

    22 闭包作为参数使用

    只有一个闭包参数时可以使用尾随闭包,其他要加闭包的参数名字
    对于单表达式闭包可以,隐式使用返回(return)

    //推荐
     UIView.animateWithDuration(1.0) {
      self.myView.alpha = 0
    }
    
    UIView.animateWithDuration(1.0,
      animations: {
        self.myView.alpha = 0
      },
      completion: { finished in
        self.myView.removeFromSuperview()
      }
    )
    
    //不推荐
    UIView.animateWithDuration(1.0, animations: {
      self.myView.alpha = 0
    })
    
    UIView.animateWithDuration(1.0,
      animations: {
        self.myView.alpha = 0
      }) { f in
        self.myView.removeFromSuperview()
    }
    
    // 隐式返回
    attendeeList.sort { a, b in
      a > b
    }
    

    相关文章

      网友评论

          本文标题:Swift 代码规范总结更新

          本文链接:https://www.haomeiwen.com/subject/bdsguhtx.html