Raywenderlich.com's swift Programming style guide

Source: Internet
Author: User
Tags access properties closure function definition



Translated from: Https://github.com/raywenderlich/swift-style-guide



This style guide may be different from what you see elsewhere, and our focus is mainly on the readability of the Internet and articles. This programming style guide was created to maintain the elegance and consistency of code in our books, tutorials, and Starter kits------Although we have worked with many different authors.



Our primary goal is simplicity, readability and simplicity.






Are you writing a objective-c? Take a look at our objective-c style guide.


Folder
Naming for classes, methods, variables, etc. uses a camel-like (CamelCase) named descriptive narrative. The first letter of the class name and the global constant is capitalized, and the method and variable names begin with lowercase. Suggestions:
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 both the function and the Init method, all the parameters have a well-named parameter name, unless the context is already very clear. Assuming that you include the parameter name when calling the function externally, you will make the function call 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. In accordance with Apple's custom, refer to the first number of parameters in the method name:

Class Guideline {  
func combinewithstring (incoming:string, options:dictionary?) { ... } 
 Func Upvoteby (amount:int) {...}}

When we need to refer to the method in the article, we want to include all the necessary parameter names from the caller's perspective. Suppose the context is very clear. and the exact method signature is not important. You can just use the name.







Call Convertpointat (column:row:)from your own Init method implementation.



Assuming you 've achieved Didselectrowatindexpath, remember to deselect rows after you've finished working.



You cannot call DataSource's TableView (_:cellforrowatindexpath:) directly.
The class prefix Swift's type has its own active module namespace, and the result is that the prefix must not be used in order to reduce the name conflict. Assuming there are two conflicting names from different modules, you can eliminate the ambiguity by adding the module name to the type name:
Import Mymodulevar MyClass = Mymodule.myclass ()
You should notPrefix the swift type. Assuming you need to expose a swift type for use in Objective-c, you can also provide a suitable prefix, like this:
@objc (Rwtchicken) class Chicken {   ...}

Interval
    • Use 2 spaces to indent instead of tab, which can save space and help prevent line breaks.


      Be sure to set it up in your xcode preferences.


    • The curly braces of the method and the curly braces for other statements (If/else/switch/while, and so on) are always opened on the same line as the statement and closed on a new line.
Suggestions:
if user.isHappy {
  //Do something
} else {
  //Do something else
}
Not recommended:
if user.isHappy
{
    //Do something
}
else {
    //Do something else
}
    • There should be exactly one empty line between the methods. This can make the structure look clearer.


      The function is separated by a blank line within the method. But assuming that there are too many segments, it often means that you need to re-create multiple methods.


Stare at the time of need. Use gaze to explain a particular piece of code WhyTo do so, the gaze must be kept up to date or deleted altogether. Avoid embedding large stares into your code, and you should make your own documentation of the code itself. exception: This does not apply to situations where a document is generated through gaze.




Classes and structs Here is a sample of a very good style definition class:
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 clearly shows the following rules:
    • For attributes, variables, constants, parameter definitions, and other declarations specifying the type, add a space after the colon instead of the preceding one, for example: X:int and Circle:shape.
    • For multiple variables, assuming they have the same structure and context (for example, X, y), they are defined on the same line.
    • The getter/setter definition of the Indent property.
    • Do not add the default modifier like interal. Same as when overwriting a method. Do not write its access modifier again on the method.
Self is used to avoid using self. Because Swift does not need to use self to access properties in an object or to invoke methods on an object. The only reason for the need to use self is when initializing a class or struct, the difference between the open attribute and the parameter name is:
class BoardLocation {
  let row: Int, column: Int

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

A function definition defines a function declaration (including an opening parenthesis) on a single line:
func reticulateSplines(spline: [Double]) -> Bool {
  // reticulate code goes here
}
For functions that have long signatures, add a newline character to the appropriate place. and add an extra indent for the next few lines:
func reticulateSplines(spline: [Double], adjustmentFactor: Double,
    translateConstant: Int, comment: String) -> Bool {
  // reticulate code goes here
}

Closures use the following closure syntax (Trailing Closure Syntax) as much as possible.





In either case, the number of references in the closure has descriptive names:


return SKAction.customActionWithDuration(effect.duration) { node, elapsedTime in 
  // more code goes here
}
A single-line expression closure with clear context, using an implicit return:
attendeeList.sort { a, b in
  a > b
}

Type if possible, always use Swift's native type.





Swift provides bridging (bridging) to OBJECTIVE-C functionality, and you can use the complete method of objective-c when needed:


Suggestions:
let width = 120.0                                    //Double
let widthString = (width as NSNumber).stringValue    //String
Not recommended:
let width: NSNumber = 120.0                                 //NSNumber
let widthString: NSString = width.stringValue               //NSString
In the code using the sprite kit, using CGFloat can make the code more concise, avoiding too many types of conversions at the same time.








Constant constants are defined using Letkeyword, and variables are defined using Varkeyword. Use let to properly define values that will never be changed. You may therefore find yourself using a let far more than using Var. Tips:A technique that can help us achieve this is to define everything as a constant and replace it with a variable only when the compiler gives an error.
Optional use? Defines the return value of the variable and method to optional. Indicates that the value can accept nil. Suppose you know that an instance variable must be initialized before use, as the Viewdidload method will set all the sub-views, you can use! Do an implicit unpacking of this variable. When visiting a optional value, assume that the value is only visited once, or that there are too many optioanl values associated. Then use optional Chaining:
Myoptional?

. anotherone?. Optionalview?. Setneedsdisplay ()

Suppose you want to make it easier to split a package and then run multiple operations. Binding with optional:
if let view = self.optionalView {
  // do many things with view
}

The initialization of a struct using Swift's native struct initialization is better than the previous Cggeometry construct method. Suggestions:
let bounds = CGRect(x: 40, y: 20, width: 120, height: 80)
var centerPoint = CGPoint(x: 96, y: 42)
Not recommended:
let bounds = CGRectMake(40, 20, 120, 80)
var centerPoint = CGPointMake(96, 42)

Type judgment The Swift compiler is able to determine the data types of variables and constants. You can explicitly declare a data type by providing a type alias (that is, after the colon). But most of the cases do not need to do so.







We like the concise code. Let the compiler determine the types of variables and constants. (In some cases it may be necessary to declare explicitly, for example, if you assign a floating-point type to a variable, Swift will judge the variable as double.) Instead of float, assuming you must use float, you can simply declare it explicitly)
Suggestions:
let message = "Click the button"
var currentBounds = computeViewBounds()
Not recommended:
let message: String = "Click the button"
var currentBounds: CGRect = computeViewBounds()
remark:In accordance with this principle: it is more important to take a name with descriptive narrative than anything else.
Syntax sugar it is better to use a shortcut than to use the full syntax when defining a generic type.







Suggestions:
var deviceModels: [String]
var employees: [Int: String]
var faxNumber: Int?


Not recommended:
var deviceModels: Array<String>
var employees: Dictionary<Int, String>
var faxNumber: Optional<Int>

The control flow for-in is better than the complete for-condition-increment style: recommended:
for _ in 0..<3 {
  println("Hello three times")
}

for person in attendeeList {
  // do something
}
Not recommended:
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
}

Semicolon Swift no longer requires a semicolon after each line of your code, only if you want to put multiple statements on the same line. Do not separate multiple statements in one line with semicolons.







There is only one exception: a semicolon must be used when constructing for-condition-increment. However, use the for-in loop as much as you can.







Suggestions:
var swift = "Not a scripting language"
Not recommended:
var swift = "Not a scripting language";
remark:Swift is very different from JavaScript, and omitting semicolons in JavaScript is often considered unsafe.
The language uses American English to adapt to Apple's API. Suggestions:
var color = "Red"
Not recommended:
var colour = "Red"

Smiley face is a very prominent feature of raywenderlick.com site. The right smiley face means a great joy and excitement for programming. This is very important. Using the right bracket] represents the biggest smile that can be recorded by the ASCII art. The closing parenthesis) indicates that a half-hearted smiley is created, so this is undesirable.







Suggestions:
:]
Not recommended:
:)

The hero's style guide is the result of the most fashionable raywenderlich.com team members working together:
    • Soheil Moayedi Azarpour
    • Scott berrevoets
    • Eric Cerney
    • Sam Davies
    • Evan Dekhayser
    • Jean-pierre Distler
    • Colin Eberhardt
    • Greg Heo
    • Matthijs Hollemans
    • Erik Kerber
    • Christopher Lapollo
    • Andy Pereira
    • Ryan Nystrom
    • Cesare Rocchi
    • Ellen Shapiro
    • Marin Todorov
    • Chris Wagner
    • Ray Wenderlich
    • Jack Wu
Pay tribute to the team of Nicholas Waynik and objective-c style guides!







Our inspiration comes from Apple's swift reference material:
    • The Swift programming Language
    • Using Swift with Cocoa and objective-c
    • Swift Standard Library Reference


Raywenderlich.com's 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.