Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Swift programming style guide


May 21, 2021 Swift


Table of contents


Language

Spell in American English to match Apple's API

Optimization:

var color = "red"

Not recommended:

var colour = "red"

Interval

  • Use 2 spaces for indentation instead of Tab, which saves spaces and prevents line changes. Make sure that you set it up in the Xcode configuration item.
  • The parenthesis of the method and other if / else / switch / switch while always start on the same line as the statement, but end in the new line.

Optimization:

if user.isHappy {
  //Do something
} else {
  //Do something else
}

Not recommended:

if user.isHappy
{
    //Do something
}
else {
    //Do something else
}
  • Methods should always be separated by a blank line to improve visual and structural clarity. Blank characters in a method are used to isolate function blocks, but if there are too many such function blocks in a method, it usually means that you need to refactor it into multiple methods.

Comments

  • Use comments when needed to explain why a piece of code does this. Comments must always follow up on the code, otherwise they can be deleted.
  • Avoid using blocked comments in your code because your code should be as self-documented as possible. Exception: This rule does not apply to block comments used to generate documents.

Named

Use the hump method to take a descriptive name for classes, methods, variables, and so on. The class and constant names of the module range should begin with capital letters, while method names and variable names should begin with lowercase letters.

Optimization:

let MaximumWidgetCount = 100

class WidgetContainer {
  var widgetButton: UIButton
  let widgetHeightPercentage = 0.85
}

Not recommended:

let MAX_WIDGET_COUNT = 100

class app_widgetContainer {
  var wBut: UIButton
  let wHeightPct = 0.85
}

For normal functions and constructor names, it is more recommended to name all parameters unless the context is very clear. If the external parameter name makes the function call more readable, bring it with you.

func dateFromString(dateString: NSString) -> NSDate
func convertPointAt(#column: Int, #row: Int) -> CGPoint
func timedAction(#delay: NSTimeInterval, perform action: SKAction) -> SKAction!

// 会被这样调用
dateFromString("2014-03-14")
convertPointAt(column: 42, row: 13)
timedAction(delay: 1.0, perform: someOtherAction)

For methods, follow Apple's naming criteria and mention the first parameter in the method name:

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

In all references to the function, including tutorials, books, and reviews, consider from the caller's point of view and include all the necessary parameter names:

dateFromString()函数真是太棒了。
在你的init()方法中调用convertPointAt(column:, row:)timedAction(delay:, perform:)的返回值可能为nilGuideline对象只有两个方法:combineWithString(options:)upvoteBy()。
你不应该直接调用数据源方法tableView(cellForRowAtIndexPath:)

Class prefix

The types in Swift are automatically added to the namespace of the module that contains them. S o even to minimize the possibility of naming conflicts, prefixes are unnecessary. If two names from different modules conflict, you can eliminate ambiguity by adding the module name before the name:

import MyModule

var myClass = MyModule.MyClass()

You should not prefix the type you created.

If you need to expose the Swift type to objective-C environments, please provide the appropriate prefix as follows (refer to the Objective-C Style Guide for naming the prefix):

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

Semicolon

In Swift, a sign after each statement is not required. You only need to add a sign if you have more than one statement in a row.

Do not write multiple statements in a line separated by a sign.

The only exception to this rule is for-conditional-increment structure, where a sign is required. However, use a different structure, the for-in loop, whenever possible.

Optimization:

var swift = "not a scripting language"

Not recommended:

var swift = "not a scripting language";

Note: Swift is different from JavaScript, where it is often unsafe to omit a sign.

Classes and structures

The following code is a very standard class definition, please refer to:

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 (\(x),\(y)) with an area of \(computeArea())"
  }

  func computeArea() -> Double {
    return M_PI * radius * radius
  }  
}

The above example illustrates the following stylism guidelines:

  • When you define a type for a property, variable, constant, parameter declaration, and other statements, the colon is followed by a space instead of the preceding one, x: Int and Circle: Shape
  • To indent the getter and setter definitions as well as the property observer.
  • If multiple variables, structures have the same purpose or context, define them on the same line.

Self

Avoid using self, considering that accessing an object's properties in Swift or the method that calls it does not require self

The only self need to use self is to use it to distinguish between property names and parameters when initializing a class or structure:

class BoardLocation {
  let row: Int, column: Int

  init(row: Int,column: Int) {
    self.row = row
    self.column = column
  }
}

Function declaration

Keep the function declaration short and sharp, try to complete the declaration in one line, and also include parentheses:

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

For functions with long parameters, break the line in the appropriate position and indent the subsequent rows one level:

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

Closure

Use the tail closure syntax as much as possible. In all cases, you need to give the closure parameter a descriptive name:

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

For context-clear single expression closures, use an implicit return value:

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

Type

Use Swift native types as much as possible. Swift provides a bridge to Objective-C so you can still use all of the Objective-C methods when you need them:

Optimization:

let width = 120.0                                           //Double
let widthString = width.bridgeToObjectiveC().stringValue    //String

Not recommended:

let width: NSNumber = 120.0                                 //NSNumber
let widthString: NSString = width.stringValue               //NSString

In Sprint Kit's code, CGFloat can avoid too many conversions and make the code simple and clear, use it.

Constant

Constants are let keyword, while variables are var keyword. I f any value is an invarian, use let keyword to define it properly. Finally you'll find that you let use let far more far

Tip: There's a way to help you comply with this rule, define all values as constants, and then change them to variables when prompted by the compiler.

Optionals

In the event that the nil value is possible, the variable and the function return the type of the value through ? Defined as Optional.

Pass ! only if it is determined that the instance variable will be used after ! Define it as an implicit unplubase type, such as a viewDidLoad

When accessing an Optional value, use the chainEdOptional syntax if the value is accessed only once, or if you need to access multiple Optional values in a row after that:

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

For situations that require the Option value to be unziped once and then multiple operations, it is easier to use Optional binding:

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

Type inference

Swift's compiler can infer the type of variable and constant. Explicit types can be provided through type aliases that indicate their type after colons, although this is not necessary in most cases.

Keep the code compact, and then have the compiler infer the type of variable and constant.

Optimization:

let message = "Click the button"
var currentBounds = computeViewBounds()

Not recommended:

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

Note: Following this guideline means that descriptive names are more important than before.

Control the flow

For for loop, the for-in is preferred over the for-condition-increment style:

Optimization:

for _ in 0..5 {
  println("Hello five times")
}

for person in attendeeList {
  // do something
}

Not recommended:

for var i = 0; i < 5; i++ {
  println("Hello five times")
}

for var i = 0; i < attendeeList.count; i++ {
  let person = attendeeList[i]
  // do something
}

Smiling face

Smiley faces are raywenderlich.com particularly important style features for people with a smiley face. U sing the right smiley face can indicate endless joy and excitement about a topic. I t was ] it represents the largest smiley face in ASCII art. Closed parentheses ) recommended because they give a "hehe" feel.

Optimization:

:]

Not recommended:

:)

The goal of this style guide is to make Swift code cleaner and more readable.

Origin: Http://letsswift.com/2014/07/swift-style-guide/