Go Swift Programming Style Guide

Source: Internet
Author: User
Tags class definition uppercase letter

Language

Use American English spelling to match Apple's API

Preferred: var color = "Red" is not recommended: var colour = "Red"
Interval
    • Use 2 spaces to indent and not tab so you can save space and prevent line breaks. Make sure the settings are set in the Xcode configuration item.
    • The curly braces of the method and other curly braces (/// if else switch while and so on) always start with the statement on the same line, but end in a new line.
Preferred: If User.ishappy {  //do something} else {  //do something else} is 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. The whitespace in the method is used to isolate the function block, but if there are too many such blocks in a method, it usually means that you need to refactor it into multiple methods.
Comments
    • Use annotations when needed to explain why a piece of code is doing this. Note You must always follow the code, or delete it.
    • Because the code should be as self-documenting as possible, avoid using blocks of comments in your code. Exception: This rule does not apply to block comments that are used to generate documents.
Named

Use the Hump method to take a descriptive name for classes, methods, variables, and so on. The class name of the module scope and the constant name begin with an uppercase letter, and the method name and the variable name should start with a lowercase letter.

Preferred: let Maximumwidgetcount = 100class widgetcontainer {  var widgetbutton:uibutton let  widgetheightpercentage = 0.85} Not recommended: let Max_widget_count = 100class 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 meaning is very clear. If the name of the external parameter makes the function call more readable, take it with you.

Func datefromstring (datestring:nsstring), Nsdatefunc convertpointat (#column: int, #row: int), Cgpointfunc time Daction (#delay: Nstimeinterval, perform action:skaction) skaction!//will be called datefromstring ("2014-03-14") Convertpointat (column:42, row:13) timedaction (delay:1.0, perform:someotheraction)

For the method, follow the Apple naming standard 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 functions (including tutorials, books, and reviews), consider the caller's perspective and include all necessary parameter names:

DatefromstringThe () function is really great.init () method call convertpointat column:, Row:). timedaction (delay:, Perform The return value of the:) may be nilguideline object only two methods: combinewithstring< Span class= "pun" > (options:) with upvoteby ().  You should not call the data source method directly tableview ( cellforrowatindexpath:).  
Class Prefix

Types in Swift are automatically added to the namespace of the module that contains them. So even to minimize the likelihood of naming conflicts, prefixes are not necessary. If two names from different modules conflict, you can disambiguate by adding a module name in front of the name:

Import Mymodulevar MyClass = Mymodule.myclass ()

You should not prefix a type that you create.

If you need to expose the swift type to use in a objective-c environment, provide the appropriate prefix as follows (refer to the Objective-c style guide for the naming of the prefixes):

@objc (Rwtchicken) class Chicken {   ...}
Semicolon

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

Do not write multiple statements separated by semicolons in one line.

The only exception to this rule is the for-conditional-increment structure, in which the semicolon is required. However, use a different structure, as much as possible, to for-in loop.

Preferred: var swift = "Not a scripting language" is not recommended: var swift = "Not a scripting language";

Note: Unlike JavaScript, it is often unsafe to omit semicolons in the latter.

Class and struct

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 A area of \ (Computearea ()) "  }  func Computearea (), Double {    return m_pi * radius * radius  }  }

The above example illustrates a few stylistic guidelines:

    • When defining types for attributes, variables, constants, argument declarations, and other statements, the colon is followed by a space instead of the preceding, such as: x: Int heel Circle: Shape .
    • The getter and setter definitions as well as the property observer are indented.
    • If multiple variables, structures have the same purpose or context, are defined on the same line.
Self

Avoid using it, considering that accessing the properties of an object in Swift or the method that calls it does not need to be used self .

selfThe only reason to use it is to use it to differentiate between property names and parameters when initializing a class or struct:

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 concise, try to complete the declaration in one line, and also include the opening parenthesis:

Funcreticulatesplines(spline:Double[]),Bool{// Reticulate code goes here}          

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

Func reticulatesplines (spline:double[], adjustmentfactor:double,    translateconstant:int, comment:string) Bool {  //Reticulate code goes here}
Closed Package

Use the trailing closure syntax whenever possible. In all cases, a descriptive name is required for the closure parameter:

Return Skaction.customactionwithduration (effect.duration) {node, elapsedtime in   //More code goes here}

For a single-expression closure with a clear context, use the implicit return value:

Attendeelist.sort {A, B in  a > B}
Type

Use the Swift native type as much as you can. Swift provides bridging of the objective-c so that all objective-c methods can still be used when needed:

Preferred: let width = 120.0                                           //doublelet widthstring = Width.bridgetoobjectivec (). StringValue    //string Not recommended: let width : NSNumber = 120.0                                 //nsnumberlet widthstring:nsstring = Width.stringvalue               //nsstring

In the code of the sprite kit, if CGFloat you can avoid too many transformations and make the code simple and straightforward, then use it.

Constant

Constants let are defined by keywords, and variables are var defined using keywords. If any value is a invariant, then use the let keyword to define it appropriately. Finally you will find yourself liking to use let far more than far .

Tip: There is a way to help you conform to the rule, define all values as constants, and then change them to variables when prompted by the compiler.

Optionals

In the case where the nil value is possible, the type of the variable followed by the function return value is ? defined as optional.

Only if the instance variable is determined to be used after initialization is ! defined as an implicit unpacking type (implicitly unwrapped Types), such as a child view that will be viewDidLoad created in.

When accessing an optional value, use the chained optional syntax if the value is only accessed once, or if you need to continuously access multiple optional values later:

Myoptional?. anotherone?. optionalview?. setneedsdisplay()         

For situations where you need to untie the optional value once and then perform multiple operations, it is more convenient to use the optional binding:

If let view = Self.optionalview {  //Does many things with view}
Type inference

Swift's compiler can infer the types of variables and constants. You can provide an explicit type by type alias (which is indicated by its type after the colon), but this is not necessary in most cases.

Keep the code compact and let the compiler infer the type of the variable and the constant.

Preferred: Let message = "click the button" var currentbounds = Computeviewbounds () is not recommended: let message:string = "click the button" VA R currentbounds:cgrect = Computeviewbounds ()

Note: Following this guideline means that a descriptive name is more important than the previous one.

Control flow

For for loops, preferred for-in style rather than for-condition-increment style:

Preferred: For _ in 0..5 {  println ("Hello five times")}for the person in attendeelist {  //do something} is not recommended: for var i = 0; < 5; i++ {  println ("Hello five times")}for var i = 0; i < Attendeelist.count; i++ {let person  = attendeelist[i]
   
    //do something}
   
Smiling face

A smiley face is a particularly important stylistic feature for raywenderlich.com. Using the right smiley face can indicate the joy and excitement of a topic. ]It is chosen because it can represent the most smiley face in the art of ASCII. The closed parenthesis ) is not recommended because it gives a feeling of "hehe".

Optimization:

:]

It is not recommended to use:

:)

This article is copyrighted by raywenderlich.com, the official raywenderlich.com Swift Style Guide project and all contributors.

Translator translation is used only for the dissemination of knowledge.

The goal of this style guide is to make swift code more concise and readable.

Go Swift Programming Style Guide

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.