Swift编码规范

从其他地方整理了一些编码规范的资料,分享给大家。YoY

这我们的首要目标是简洁,可读性和简单性。

1.命名(Naming)

使用驼峰命名规则和描述性的名称来定义类、方法、变量等。类名和模块中的常量的第一个字母应该大写,而方法名和变量应该开始用小写字母。
Use descriptive names with camel case for classes, methods, variables, etc. Class names and constants in module scope should be capitalized, while method names and variables should start with a lower case letter.

Preferred:
let MaximumWidgetCount = 100
class WidgetContainer {
   var widgetButton: UIButton  
let widgetHeightPercentage = 0.85
}
Not Preferred:
let MAX_WIDGET_COUNT = 100
class app_widgetContainer {  
    var wBut: UIButton  
    let wHeightPct = 0.85
}

对于方法和init函数,需要对所有参数进行命名除非上下文是非常清楚的。包括外部的参数名称,如果它使函数调用更具可读性。
For functions and init methods, prefer named parameters for all arguments unless the context is very clear. Include external parameter names if it makes function calls more readable.

func dateFromString(dateString: NSString) -> NSDate
func convertPointAt(#column: Int, #row: Int) -> CGPoint
func timedAction(#delay: NSTimeInterval, perform action: SKAction) -> SKAction!
// would be called like this:
dateFromString("2014-03-14")
convertPointAt(column: 42, row: 13)
timedAction(delay: 1.0, perform: someOtherAction)

对于方法,按照苹果关于方法第一个参数的标准:
For methods, follow the standard Apple convention of referring to the first parameter in the method name:

class Guideline {  
    func combineWithString(incoming: String, options: Dictionary?) {
        ... 
    }  
   func upvoteBy(amount: Int) { 
       ... 
    }
}

当在文章中(教程,书籍,评论)包含函数代码是,需要从调用者的角度考虑所需要的参数名称。如果上下文是明确的,确切的签名并不重要,你可以只使用方法名。
When referring to functions in prose (tutorials, books, comments) include the required parameter names from the caller's perspective. If the context is clear and the exact signature is not important, you can use just the method name.
Call convertPointAt(column:row:) from your own init implementation.
If you implement didSelectRowAtIndexPath, remember to deselect the row when you're done.
You shouldn't call the data source method tableView(_:cellForRowAtIndexPath:) directly.

2.类前缀(Class Prefixes)

Swift会自动为模块中的类型增加命名空间。因此,不需要为避免名字冲突为类型增加前缀。如果不同模块的两个名字有冲突,那么可以通过模块名来解决合格问题。
Swift types are all automatically namespaced by the module that contains them. As a result, prefixes are not required in order to minimize naming collisions. If two names from different modules collide you can disambiguate by prefixing the type name with the module name:

import MyModulevar myClass = MyModule.MyClass()

你不需要为你的Swift类型增加前缀

You should not add prefixes to your Swift types.

如果你需要编写在Objective-C中使用的Swift类型,你可以各一个适当的前缀

@objc (RWTChicken) class Chicken {   
    ...
}

3.空白(Spacing)

• 使用缩进2个空格,而不是制表符,以节省空间,并有助于防止换行。请务必在Xcode中设置此偏好。
Indent using 2 spaces rather than tabs to conserve space and help prevent line wrapping. Be sure to set this preference in Xcode.
• 方法括号和大括号等(if/else/switch/while等)总是在同一行语句打开在新行关闭。

Method braces and other braces (if/else/switch/while etc.) always open on the same line as the statement but close on a new line.
Preferred:
if user.isHappy {
  //Do something
} else {
 //Do something else
}
Not Preferred:
if user.isHappy
{
    //Do something
}
else {
    //Do something else
}

• 为了阅读方便应该在方法之间保持一个空行以更好的组织代码。在方法中空行应该分割功能块,但如果一个方法有太多的功能块,那么通常意味着你应该重构到多个方法中。

    There should be exactly one blank line between methods to aid in visual clarity and organization. Whitespace within methods should separate functionality, but having too many sections in a method often means you should refactor into several methods.

4.注释(Comments)

当需要的时候,使用注释来解释特定代码的功能,注释必须保持最新或删除。避免在代码块内的大块注释,该代码应该是自我描述的。例外:这并不适用于那些用来生成文档的注释。
When they are needed, use comments to explain why a particular piece of code does something. Comments must be kept up-to-date or deleted.
Avoid block comments inline with code, as the code should be as self-documenting as possible. Exception: This does not apply to those comments used to generate documentation.

5.类和结构(Classes and Structures)

下面是一个较好的类定义格式
Here's an example of a well-styled class definition:

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

上面的示例提供了较好的编码规范指南:
The example above demonstrates the following style guidelines:
• 属性,变量,常量,参数的类型和分号之间保持一个空格,如:x: Int 和 Circle: Shape

Specify
types for properties, variables, constants, argument declarations and other statements with a space after the colon but not before, e.g. x: Int, and Circle: Shape.
• 如果多个变量和结构拥有相同的目的或上下文,那么在一行里定义他们

    Define multiple variables and structures on a single line if they share a common purpose / context.

• 缩进getter、setter方法和属性观察器

        Indent getter and setter definitions and property observers.

• 不需要增加默认修饰比如internal。同样,覆盖的方法时,不要重复添加访问修饰符。

    Don't add modifiers such as internal when they're already the default. Similarly, don't repeat the access modifier when overriding a method.

6.使用self(Use of Self)

为了简洁,避免使用self因为Swift并不需要用它来访问对象的属性或调用其方法。
For conciseness, avoid using self since Swift does not require it to access an object's properties or invoke its methods.
当需要在初始化代码中区分属性名称和参数以及在闭包中明确引用属性时使用self:
Use self when required to differentiate between property names and arguments in initializers, and when referencing properties in closures to make capture semantics explicit:

class BoardLocation {
  let row: Int, column: Int

  init(row: Int,column: Int) {
    self.row = row
    self.column = column
    let closure = { () -> () in
      println(self.row)
    }
  }
}

7.定义函数(Function Declarations)

对于较短的函数定义,需要在一行中定义:
Keep short function declarations on one line including the opening brace:

 func reticulateSplines(spline: [Double]) -> Bool {
  // reticulate code goes here
}

对于有很长签名的函数,需要在适当的位置添加换行并且新行需要有额外的缩进。
For functions with long signatures, add line breaks at appropriate points and add an extra indent on subsequent lines:

func reticulateSplines(spline: [Double], adjustmentFactor: Double,
    translateConstant: Int, comment: String) -> Bool {
  // reticulate code goes here
}

8.闭包(Closures)

尽可能使用后关闭语法。在所有情况下,闭包的参数需要有一个描述性的名称:
Use trailing closure syntax wherever possible. In all cases, give the closure parameters descriptive names:

return SKAction.customActionWithDuration(effect.duration) { node, elapsedTime in 
// more code goes here
}

对于只有一行表达式的闭包,如果上下文清晰的话可以隐式返回。
For single-expression closures where the context is clear, use implicit returns:

attendeeList.sort { a, b in
  a > b
}

8.类型(Types)

尽可能地使用Swift原生类型。Swift提供了对Objective-C的桥接所以在需要的时候仍然可以使用全部的Objective-C方法:
Always use Swift's native types when available. Swift offers bridging to Objective-C so you can still use the full set of methods as needed.

Preferred:
let width = 120.0                                    //Double
let widthString = (width as NSNumber).stringValue    //String
Not Preferred:
let width: NSNumber = 120.0                                 //NSNumber
let widthString: NSString = width.stringValue               //NSString

在Sprite Kit代码中,使用CGFloat,如果它使代码更简洁,避免过多的转换。
In Sprite Kit code, use CGFloat if it makes the code more succinct by avoiding too many conversions.

9.常量(Constants)

常量通过let关键字定义,而变量使用var关键字定义。任何值如果是一个不变量,那么请使用let关键字恰如其分地定义它。最后你会发现自己喜欢使用let远多于far。
Constants are defined using the let keyword, and variables with the var keyword. Any value that is a constant must be defined appropriately, using the let keyword. As a result, you will likely find yourself using let far more than var.
Tip:有一个方法可以帮你符合该项规则,将所有值都定义成常量,然后编译器提示的时候将其改为变量。
Tip: One technique that might help meet this standard is to define everything as a constant and only change it to a variable when the compiler complains!

可选的(Optionals)

在nil值可能出现的情况下,将变量跟函数返回值的类型通过?定义成Optional。
Declare variables and function return types as optional with ? where a nil value is acceptable.
只有在确定实例变量会在初始化之后才被使用的情况下,通过 ! 将其定义为隐式解包类型(Implicitly Unwrapped Types),比如说会在viewDidLoad中被创建的子视图。
Use implicitly unwrapped types declared with ! only for instance variables that you know will be initialized later before use, such as subviews that will be set up in viewDidLoad.
在访问一个Optional值时,如果该值只被访问一次,或者之后需要连续访问多个Optional值,请使用链式Optional语法:
When accessing an optional value, use optional chaining if the value is only accessed once or if there are many optionals in the chain:

myOptional?.anotherOne?.optionalView?.setNeedsDisplay()

对于需要将Optional值解开一次,然后进行多个操作的情况,使用Optional绑定更为方便:
Use optional binding when it's more convenient to unwrap once and perform multiple operations:

if let view = self.optionalView {
  // do many things with view
}

10.初始化结构体(Struct Initializers)

使用Swift原生的结构体初始化方法,而不是使用陈旧的CGGeometry构造方法
Use the native Swift struct initializers rather than the legacy CGGeometry constructors.

Preferred:
let bounds = CGRect(x: 40, y: 20, width: 120, height: 80)
var centerPoint = CGPoint(x: 96, y: 42)
Not Preferred:
let bounds = CGRectMake(40, 20, 120, 80)
var centerPoint = CGPointMake(96, 42)

11.类型推断(Type Inference)

Swift的编译器可以推断出变量跟常量的类型。可以通过类型别名(在冒号后面指出其类型)提供显式类型,不过大多数情况下这都是不必要的。
The Swift compiler is able to infer the type of variables and constants. You can provide an explicit type via a type alias (which is indicated by the type after the colon), but in the majority of cases this is not necessary.
保持代码紧凑,然后让编译器推断变量跟常量的类型。
Prefer compact code and let the compiler infer the type for a constant or variable.

Preferred:
let message = "Click the button"
var currentBounds = computeViewBounds()
Not Preferred:
let message: String = "Click the button"
var currentBounds: CGRect = computeViewBounds()

注意:遵循这条准则意味着描述性强的名称比之前更为重要了。
NOTE: Following this guideline means picking descriptive names is even more important than before.

12.语法糖(Syntactic Sugar)

使用类型定义个快捷语法而不要使用完整的语法
Prefer the shortcut versions of type declarations over the full generics syntax.

Preferred:
var deviceModels: [String]
var employees: [Int: String]
var faxNumber: Int?
Not Preferred:
var deviceModels: Array<String>
var employees: Dictionary<Int, String>
var faxNumber: Optional<Int>
13.控制流(Control Flow)

对于for循环,优选for-in风格而不是for-condition-increment风格
Prefer the for-in style of for loop over the for-condition-increment style.

Preferred:
for _ in 0..<3 {
  println("Hello three times")
}
for person in attendeeList {
  // do something
}
Not Preferred:
for var i = 0; i < 3; i++ {
   println("Hello three times")
}
for var i = 0; i < attendeeList.count; i++ {
   let person = attendeeList[i]
  // do something
}

14.分号(Semicolons)

Swift在任何语句后都不需要分号,分号仅在你将多个语句写在一行时有用(用于区分语句)
Swift does not require a semicolon after each statement in your code. They are only required if you wish to combine multiple statements on a single line.
不要将多个语句写在一行然后用分号区分
Do not write multiple statements on a single line separated with semicolons.
这个规则的唯一例外是for语句,它需要分号。然而,在可能的情况下尽量使用可选的 for-in 语句
The only exception to this rule is the for-conditional-increment construct, which requires semicolons. However, alternative for-in constructs should be used where possible.

Preferred:
var swift = "not a scripting language"
Not Preferred:
var swift = "not a scripting language";
注意:Swift与javascript非常不一样,javascript认为省略分号是不安全的。

NOTE: Swift is very different to JavaScript, where omitting semicolons is generally considered unsafe

15.语言(Language)

与Apple API一样使用US English 拼写,尽量使用英语的拼写方式。
Use US English spelling to match Apple's API.

Preferred:
var color = "red"
Not Preferred:
var colour = "red"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容