preface

The purpose of the development specification is to ensure that the coding style of the project members is unified, and make the code beautiful, each company for the code specification is not the same, I hope this specification can give you a reference role. This article is the original, if you need to reprint, please explain the original address link.

Naming rules

  • Names in the code are strictly forbidden to use a mixture of Pinyin and English, let alone Chinese, and it is best not to start with an underscore or a dollar sign.
  • File names, classes, structs, enums, and protocols are named in the UpperCamelCase style.
  • Use the lowerCamelCase style for method names, parameter names, member variables, local variables, and enumeration members
  • Global constants are named with k prefix + UpperCamelCase;
  • Extension file, using “primitive type name + extension” as the extension file name, where primitive type name and extension also use UpperCamelCase style, such asUIView+Frame.swift;
  • Use the UpperCamelCase style for folders or groups in projects, and always use the singular.
  • The acronyms can be all uppercase or all lowercase. The case of the first letter prevails. Common acronyms include JSON and URL. Such asclass IDUtil {},func idToString() { }
  • Do not use non-standard abbreviations, such as AbstractClass “abbreviation” named AbsClass, etc., fear the name is not long, but fear the name is not clear.
  • If the file name has the plural meaning, the file name should use the plural form, such as some tool classes;

Modify specifications

  • Don’t use var when you can use let;
  • The order of modifiers is in the order of annotation, access restriction, static, and final.
  • Use the access restriction modifier to control the access restriction of classes, methods, etc.
  • When writing a method, consider whether the method will be overridden. If not, it is marked final. Final reduces compilation time.
  • When writing libraries, we need to pay attention to the selection of modifiers, follow the open closed principle;

Format specification

  • Open curly braces for classes and functions do not start on another line, leaving a space between them and their names
  • Do not use useless semicolons
  • Where whitespace appears in code
    • There is a space between the comment symbol and the comment content
    • Class inheritance, between parameter names and types, etc. Colons are not preceded by Spaces, but followed by Spaces
    • Spaces before and after any operator
    • Represents both -> sides of the return value
    • Arguments list, array, tuple, dictionary comma followed by a space
  • An empty line between methods
  • Overloaded declarations are grouped together, from least to most, in order of the number of arguments
  • Declare only one variable per line
  • If it is a long number, it is recommended to use the underscores to separate and connect the digits in groups of three or four according to the language convention.
  • Represents a static property of a singleton, usually named shared or default
  • If it is an empty block, declare {} without breaking lines between parentheses
  • It is recommended to use the original name when unpacking, as long as the unpacked and pre-unpacked names do not conflict in scope
  • Else \else if after if, followed by the closing bracket of the previous if\else if
  • In switch, left-align case and switch
  • Lines of code should be less than 100 characters long, or you should not need to scroll to read the full code within normal bounds
  • Each protocol is implemented in a separate extension

A brief specification

  • Swift is automatically generated by the struct with a non-public initialization method based on its members. If the initialization method is suitable, do not declare it yourself
  • Class and struct initialization methods do not directly call. Init, directly omit, use ()
  • If there is only one computed property of GET, ignore GET
  • When defining data, use literal form as much as possible for automatic inference, if the context is not sufficient to infer literal type, need to declare the assignment type
  • Omit the default access (internal)
  • Filter, transform, etc., preferentially use filter, map and other higher-order functions to simplify the code, and try to use the most simplified
  • When using closures, use the shortest possible shorthand
  • Use automatic inference and abbreviations when using enumeration attributes
  • Delete useless code in time
  • Try to use a variety of grammatical sugars
  • Do not use it when accessing instance members or methodsself., except for special scenarios, such as constructors
  • There is no need to add void when the method returns no value

Annotation specifications

  • Document comments use single-line comments (///) instead of multi-line comments (/***/). Multiline comments are used to describe a piece of code or design
  • The exposed classes, methods, properties, etc., must be annotated, and the corresponding methods must be annotatedThe Parameter (s),Returns,ThrowsLabel, strongly recommended⌥ ⌘ /Automatically generate document templates
  • Use landmark comments flexibly in your code, such asMARK,FIXME,TODOCan be used when multiple type definitions or multiple logic exist in the same fileMarkGroup comments
  • Try to put comments on another line instead of after the code

other

  • Do not use magic values (that is, undefined constants);
  • Function parameters must not exceed 8; Number of registers: more than 8 registers will affect efficiency.
  • Graphical literals,#colorLiteral(...).#imageLiteral(...)Use only on playground for self-practice, not in project work
  • Avoid forced unpacking and forced type mapping and use it whenever possibleif letguard letUnpack, disableThe try!Formal handling of exceptions to avoid implicit unpacking
  • Avoid nesting judgment statements too deeply and use Guard to return early
  • If the for loop has only one if judgment in the body of the function, use for where instead
  • Try to implement each protocol in a separate extension. Methods defined in extension cannot be override unless the @objc method is added to change its dispatching mode
  • Create functions first over custom operators
  • Use global namespaces such as constants, variables, methods, and so on as little as possible
  • When assigning an array or a dictionary to a row of each element, add a comma after the last option. This will make it easier to add elements in the future
  • Boolean type attributes are prefixed with is as the attribute name, and method names that return a Boolean type are prefixed with is as the method name
  • Note like modifiers are on a separate line, such as @objc, @discardableresult, etc
  • Do not add any modifiers to an extension. Modifiers are added to variables or methods within an extension
  • Use Guard to terminate conditions early to avoid nesting judgments;
  • Make good use of dictionaries to reduce judgment. Store conditions and results in dictionaries as keys and values, respectively.
  • Use assert to facilitate troubleshooting.
  • Use the capture list when using self in a closure[weak self]Circular references are avoided, and the closure begins to determine the validity of self
  • Avoid circular references when using delegates and protocols, and use weak when defining attributes

tool

SwiftLint tooltip format error

SwiftFormat tooltip and fix formatting errors

Most of the format specifications are consistent, a few of the specifications are inconsistent, and the two tools do not conflict with each other and can coexist in a project. We can enable or disable the corresponding rules through the configuration file. For the specific rules, refer to the reamme. md file of the corresponding warehouse.

The relevant specification

Swift’s official API Design Guide

The Swift coding specification released by Google


It’s important to have a tech community and a group of like-minded people, so come to my tech account and blog, and just talk about tech stuff.

  • Wechat official account: CoderStar
  • Blog: CoderStar’s Blog