Swift编码规范

命名

明确使用

  • 避免使用歧义词语
    例如,删除集合中给定位置的元素的方法
extension List {
  public mutating func remove(at position: Index) -> Element
}
employees.remove(at: x)

假如删去方法中的at话,就会产生歧义

employees.remove(x) // unclear: are we removing x?
  • 省略不必要的词语。命名中每个单词都应该使用处传递显著的信息
    例如,删除集合中的某元素
public mutating func removeElement(_ member: Element) -> Element?

allViews.removeElement(cancelButton)//语义不通

在上述例子的Element减低了方法可读性,改成下面的会更好

public mutating func remove(_ member: Element) -> Element?

allViews.remove(cancelButton) // clearer

有时,重复类型信息对于避免歧义是必要的,但通常最好使用描述参数角色而不是其类型的单词。有关详细信息,请参阅下一项。

  • 根据角色而不是类型约束命名变量,参数和关联类型。
var string = "Hello"
protocol ViewController {
  associatedtype ViewType : View
}
class ProductionLine {
  func restock(from widgetFactory: WidgetFactory)
}

以这种方式重新定位类型名称无法优化清晰度和表现力。相反,努力选择一个表达实体角色的名称。

var greeting = "Hello"
protocol ViewController {
  associatedtype ContentView : View
}
class ProductionLine {
  func restock(from supplier: WidgetFactory)
}

如果关联类型与其协议约束紧密绑定,协议名称是角色,可以通过附加Protocol到协议名称来避免冲突 :

protocol Sequence {
  associatedtype Iterator : IteratorProtocol
}
protocol IteratorProtocol { ... }
  • 补偿弱类型信息以阐明参数的作用。
    尤其是NSObjectAnyAnyObject,或者是IntString等基本类型,在下面的示例,可能声明很清晰,但是方法作用很模糊
func add(_ observer: NSObject, for keyPath: String)

grid.add(self, for: graphics) // vague

为了使其方法作用更清晰,可以在弱类型参数加上描述其角色的名词

func addObserver(_ observer: NSObject, forKeyPath path: String)
grid.addObserver(self, forKeyPath: graphics) // clear

力求流畅地使用

  • 首选能形成语法英语短语命名方法和函数
    e.g.
x.insert(y, at: z)          “x, insert y at z”
x.subViews(havingColor: y)  “x's subviews having color y”
x.capitalizingNouns()       “x, capitalizing nouns”

//not appropriate
x.insert(y, position: z)
x.subViews(color: y)
x.nounCapitalize()

在第一个或第二个参数之后,当这些参数不是调用的含义的核心时,流利性降级是可以接受的:

AudioUnit.instantiate(
  with: description, 
  options: [.inProcess], completionHandler: stopProgressBar)
  • 以"make"为开头命名工厂方法,e.g. x.makeIterator()
  • 初始化和工厂方法的第一个参数不应以短语命名, e.g. x.makeWidget(cogCount: 47)
    例如,这些调用的第一个参数不会读作与基本名称相同的短语的一部分:
let foreground = Color(red: 32, green: 64, blue: 128)
let newPart = factory.makeWidget(gears: 42, spindles: 14)
let ref = Link(target: destination)

在下文中,API作者尝试使用第一个参数创建语法连续性。

//not appropriate
let foreground = Color(havingRGBValuesRed: 32, green: 64, andBlue: 128)
let newPart = factory.makeWidget(havingGearCount: 42, andSpindleCount: 14)
let ref = Link(to: destination)
  • 根据函数和方法的附作用(side-effects)命名
  1. 没有附作用的应使用名词短语,e.g. x.distance(to:y)i.successor()
  2. 有附作用的应必要的动词短语,e.g. print(x)x.sort()x.append(y)
  3. Mutating/nonmutating 方法对命名一致,mutating方法通常具有类似语义的变化实体,但只会返回一个新的实体而不是就地更新实体
    (1)当操作由自然动词描述时,mutating方法使用命令式动词,nonmutating方法使用带"ed"或"ing"后辍的动词


    described by a verb

    Mutating:

/// Reverses `self` in-place.
mutating func reverse()

/// Returns a reversed copy of `self`.
func reversed() -> Self
...
x.reverse()
let y = x.reversed()

Nonmutating:

/// Strips all the newlines from `self`
mutating func stripNewlines()

/// Returns a copy of `self` with all the newlines stripped.
func strippingNewlines() -> String
...
s.stripNewlines()
let oneLine = t.strippingNewlines()

(2)当操作由自然名词描述时,nonmutating方法直接用名词描述,mutating方法由名词加"form"前辍描述


described by a noun
  • nonmutating方法时,布尔方法和属性用法应为有关接收者的断言,例如x.isEmptyline1.intersects(line2)
  • 描述某些东西的协议应该使用名词(例如Collection
  • 描述一个协议能力 应该使用后缀命名able,ible或ing (例如EquatableProgressReporting
  • 其他类型,属性,变量和常量的名称应使用名词。

参考文献

Swift.org

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 温德里奇规范 本规范原文链接. 规范只是一些最佳实践, 请酌情使用. 1 正确性 第一条原则, 也是最根本的原则:...
    貘鸣阅读 5,499评论 1 0
  • 翻译作者:码农网 – 豆照建 没事多看看,规范一下swift 编码习惯。 1. 代码格式 1.1 使用四个空格进行...
    彡廿阅读 4,276评论 0 2
  • 注:以下皆为翻译,如有错误或疏漏,请指正。谢谢☺ 简介 (raywenderlich 版)您看到的这份规范可能与其...
    LovelyYilia阅读 9,937评论 1 17
  • 1 命名 使用驼峰式给类,方法或者变量等。类命名必须大写,然后方法名和变量应该以小写字母开始。 eg 首选的 pr...
    Marc_Steven阅读 4,132评论 0 0
  • 皎皎明月清辉冷,当年曾照紫禁城。 干古兴亡更迭事,苦了百姓与苍生。 我本飘零江湖客,半世蹉跎无所成。 天怜我老天不...
    影曳香弄阅读 2,615评论 0 8