超全面的Swift编码规范(推荐)

2020-01-08 23:40:30丽君

可选类型

唯一使用隐式拆包可选型的场景是结合@IBOutlets,在其他场景使用非可选类型和常规可选类型,即使有的场景你确定有的变量使用的时候永远不会为nil,但这样做可以保持一致性和程序更加健壮。

不要使用as!和try!,除非万不得已。

如果对于一个变量你不打算声明为可选类型,但当需要检查变量值是否为nil,推荐使用当前值和nil直接比较,而不推荐使用if let的语法。并且nil在前变量在后。


// 推荐
if nil != someOptional {
 // 你要做什么
}
// 不推荐
if let _ = someOptional {
 // 你要做什么
}

不要使用unowned,unowned和weak修饰变量基本上等价,并且都是隐式拆包(unowned在引用计数上有少许性能优化),由于不推荐使用隐式拆包,也不推荐使用unowned变量。


// 推荐
weak var parentViewController: UIViewController?
// 不推荐
weak var parentViewController: UIViewController!
unowned var parentViewController: UIViewController

guard let myVariable = myVariable else {
 return
}

协议

在实现协议的时候,有两种方式来组织你的代码:

使用//MAKR:注释来实现分割协议和其他代码。

使用 extension 在 类/结构体已有代码外,但在同一个文件内。

请注意 extension 内的代码不能被子类重写,这也意味着测试很难进行。 如果这是经常发生的情况,为了代码一致性最好统一使用第一种办法。否则使用第二种办法,其可以代码分割更清晰。使用而第二种方法的时候,使用 // 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)")
 }
}

在创建常量的时候,使用static关键字修饰。


class MyTableViewCell: UITableViewCell {
 static let kReuseIdentifier = String(MyTableViewCell)
 static let kCellHeight: CGFloat = 80.0
}

声明单例属性可以通过下面方式进行: