iOS踩坑集swift学习

Swift开发代码规范

2019-10-18  本文已影响0人  悟饭哪

Swift开发规范

此文档与Apple官方Swift代码规范文档不冲突,只是在官方文档的基础上增加了的部分规范。

命名规范

  enum OrderStatus: Int {
      case normal
      case expired
      case paid
  }
let weAnimationDuration: TimeInterval = 0.25
    func we_checkLogin() -> Bool {
      ...
    }
  1. 如果是单纯的协议,则采用驼峰命名法,首字母大写,后缀为"protocol"。示例:SomeProtocol
  2. 如果是用来做代理的,则采用驼峰命名法,首字母大写,后缀为"delegate"。示例:OrderCellDelegate
  // 推荐:
  func namePickerView(_ namePickerView: NamePickerView, didSelectName name: String)
  func namePickerViewShouldReload(_ namePickerView: NamePickerView) -> Bool

  // 不推荐
  func didSelectName(namePicker: NamePickerViewController, name: String)
  func namePickerShouldReload() -> Bool
  @objc protocol OrderCellDelegate: class {
      // 除了自身对象之外,还有操作的控件作为参数
      func orderCell(cell: weOrderCell, didClick checkButton: UIButton)
      // 只有自身对象作为参数
      @objc optional func orderCellDidClickCheckButton(cell: weOrderCell)
    }
  1. 图片资源需要在名称中加上功能模块名,防止重复,示例:img_home_right_arrowimg_order_locate
  2. 声音资源名称表明用途即可,示例:qr_sound
  extension UIView {
      /// 移除所有子控件
      func we_removeAllSubviews() {
          ...
      }
  }
  // "HTML" 是变量名的开头, 需要全部小写 "html"
  let htmlBodyContent: String = "<p>Hello, World!</p>"
  // 推荐使用 ID 而不是 Id
  let profileID: Int = 1
  // 推荐使用 URLFinder 而不是 UrlFinder
  class URLFinder {
      ...
  }
// 推荐
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
    }
  }

编码格式

  let myValue = 20 + (30 / 2) * 3

  if 1 + 1 == 3 {
    fatalError("The universe is broken.")
  }

  func pancake() -> Pancake {
    ...
  }
  class SomeClass {
    func someMethod() {
      if x == y {
        ...
      } else {
        ...
      }
    }
  }
  class Pirate {

    // MARK: - 实例属性

    private let pirateName: String

    // MARK: - 初始化

    init() {
        /* ... */
    }
  }
  extension ViewController: OrderCellDelegate {

      func orderCell(cell: OrderCell, didClick checkButton: UIButton) {
          ...
      }
  }
  let my = MyClass()
  my.name     = "张四"
  my.age      = 10
  my.address  = "望京绿地中心"
  if someBoolean {
    // something you want
  } else {
    // something you don't want
  }

  do {
    let fileContents = try readFile("filename.txt")
  } catch {
    print(error)
  }
  // 推荐
  private static let kMyPrivateNumber: Int
  // 不推荐
  static private let kMyPrivateNumber: Int
  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).")
  }
  // 指定类型
  let pirateViewController: PirateViewController
  // 字典语法(注意这里是向左对齐而不是分号对齐)
  let ninjaDictionary: [String: AnyObject] = [
    "fightLikeDairyFarmer": false,
    "disgusting": true
  ]
  // 调用函数
  someFunction(someArgument: "Kitten")
  // 父类
  class PirateViewController: UIViewController {
    ...
  }
  // 协议
  extension PirateViewController: UITableViewDataSource {
    ...
  }

语法规范

错误示例:

  var x = [String: Int]()
  var y = [Double]()
  var z = Set<String>()
  var mySet = MyOptionSet()

正确示例:

  var x: [String: Int] = [:]
  var y: [Double] = []
  var z: Set<String> = []
  var mySet: MyOptionSet = []
  if let name = person.name, let age = person.age {
  }
  if let name = person.name as? String {
  }
  class ViewController: UIViewController {

    let cellID = "GirlCell"
    ...
  }
  func myFunctionWithManyParameters(parameterOne: String,
                                    parameterTwo: String,
                                    parameterThree: String) {

      print("\(parameterOne) \(parameterTwo) \(parameterThree)"
  }
  if myFirstVariable > (mySecondVariable + myThirdVariable)
    && myFourthVariable == .SomeEnumValue {
      // Xcode会自动缩进
      print("Hello, World!")
  }
  // 推荐
  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 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 语句更有可读性
  if operationFailed {
    return
  }
  // guard 语句这里有更好的可读性
  guard isSuccessful else {
    return
  }
  // 双重否定不易被理解 - 不要这么做
  guard !operationFailed else {
    return
  }
  // 推荐
  if isFriendly {
      print("你好, 远路来的朋友!")
  } else {
      print("穷小子, 哪儿来的?")
  }

  // 不推荐
  guard isFriendly else {
      print("穷小子, 哪儿来的?")
      return
  }
  print("你好, 远路来的朋友!")
  // 推荐
  let selector = #selector(viewDidLoad)
  view.backgroundColor = .red
  let toView = context.view(forKey: .to)
  let view = UIView(frame: .zero)

  // 不推荐
  let selector = #selector(ViewController.viewDidLoad)
  view.backgroundColor = UIColor.red
  let toView = context.view(forKey: UITransitionContextViewKey.to)
  let view = UIView(frame: CGRect.zero)

框架使用

// 带布局
let checkAllLabel = UILabel(text: "查看全部", font: dj_semiboldFont(14), color: .white, alignment: .right, superView: originalView) { (make) in
    make.center.equalTo(thirdImageView)
    make.width.equalTo(56)
    make.height.equalTo(20)
}
// 不带布局
let checkAllLabel = UILabel(text: "查看全部", font: dj_semiboldFont(14), color: .white, alignment: .right)
// UIView
view.dj_addBottomLine()             // 在底部添加分割线
view.dj_addShadow()                 // 添加阴影
view.dj_removeAllSubviews()         // 移除所有子控件
view.dj_getParentViewController()   // 获取父控制器
...
// 控制器
vc.dj_push(TestViewController())
vc.dj_present(TestViewController())
vc.dj_pop()
vc.dj_showActionSheet()
...
Functions Comment
dj_hexColor("00ff00") get a color with a hex value.
dj_pingSemiboldFont(15) get a font from the font family "PingFangSC-Semibold".
dj_isCameraAllowed() the camera authorization is allowed or not.
dj_navigationBarHeight() get the navigation bar height(adapted iPhone X or later).
dj_isEmpty(obj) an object is empty or not.
dj_isIPhoneX() the phone is iPhone X,Xs,Xs Max or not.
dj_toJson(obj) convert an object to json string.
dj_callPhone("13288889990") call a number
dj_postNotification("LoginSuccessNotification") post a notification.
more...

网络请求

后记

Have fun.

上一篇下一篇

猜你喜欢

热点阅读