Getting Started with iOS development-17 Swift Best Practices Specification (top)

Source: Internet
Author: User
Tags knowledge base

  Article Source: http://www.zretc.com/technologyDetail/432.html

  Objective

This introductory iOS development article was compiled from a series of notes that I worked on in Swiftgraphics. Most of the recommendations in this paper are well thought out, but there are other similar solutions that can still be used. Therefore, if other scenarios make sense, these scenarios are added.

This best practice is not to impose or recommend Swift's application in a program, object-oriented, or functional style. More importantly, here is a pragmatic approach. If necessary, some suggestions may be focused on object-oriented or practical solutions.

This article covers the Swift language and the Swift standard library. Even so, if you can come up with a unique swift perspective and insight, we still offer special recommendations such as Swift's use on Mac OS, IOS, WatchOS, and TV os. And how to use Swift effectively on Xcode and LLDB, this advice is also available in Hints & tips style.

This process requires a lot of effort, thanks very much to those who contributed to this article.

In addition, it can be discussed in [Swift-lang slack].

  Contributors ' Notes

Make sure that all the examples are operational (some examples may not be correct). This markdown can be converted into a Mac OS X playground.

  Golden Rule

1. In general, Apple is right to follow Apple's preferred or exemplary approach. In any case, you should follow Apple's code style, just as they are defined in the Swift programming Language book. But Apple is a big company and we'll see a lot of differences in the sample code.

2. Never write code just to reduce the amount of code. Try to rely on the auto-complete code in Xcode, automatically suggest, copy, and paste. The detailed Code description style is very useful for other code maintainers. Even so, excessive redundancy loses the important feature of Swift: type inference.

Best practices

1. Naming

Naming is named as the type name in Swift programming Language (for example: Vehiclecontroller) in the large hump naming method.

Variables and constants are named after the small hump nomenclature (for example: Vehiclename).

You should use the Swift template to name your code instead of using the style of the Objective-c class prefix (unless and objective-c successive).

Do not use any Hungarian notation (Hungarian notation) to name (for example: K is constant, M is method), you should use short naming and use Xcode type Quick Help (01.png+ click) to find out the type of the variable. Similarly, do not use the lowercase + underscore (snake_case) naming method.

The only particular thing is the name of the enum value, which requires the use of the Big Hump nomenclature (which is also followed by Apple's Swift programming Language style):

Enum Planet {case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune}

In all possible cases, the need to reduce the name and abbreviations should be avoided, and in the future you should be able to accurately indicate the type feature "Viewcontroller" without any damage or reliance on Xcode's auto-completion function. Very common abbreviations such as URLs are allowed. Abbreviations should be denoted by all uppercase letters (URLs) or all lowercase letters (URLs). Use the same rules for types and variables. If the URL is a type, it should be uppercase, and if it is a variable, it should be lowercase.

2. Notes

Comments should not be used to invalidate the code, and commenting on the code invalidates the code and affects the cleanliness of the code. If you want to remove the code, but still want to keep it in case the code will be used later, you should rely on Git or bug tracker.

3. type inference

Where possible, use Swift's type inference to reduce redundant type information. For example, the correct wording:

var currentlocation = location ()

Instead of:

var currentlocation:location = location ()

4. SelfInference

Let the compiler infer self in all allowed places. You should explicitly use self in setting parameters in init and non-escaping closures. For example:

struct Example {let name:string init (name:string) {self.name = name}}

5. parameter list type inference

Specifying a parameter type in a closure expression (closure expressions) can result in more verbose code. Only when you need to specify a type.

let people = [("Mary", "a"), ("Susan", +), ("Charlie",),] let strings = People.map () {(name:string, age:int) String in return "(name) was (age) years-old"}

If the compiler can infer the type, you should remove the type definition.

Let strings = People.map () {(name, age) in return "(name) was (age) years"}

Naming with sorted parameter numbers ("$", "$", "$") is a better way to reduce redundancy, which can often be used to fully match the parameter list. Use a number name only if there is not too much information in the parameter name of closure. (such as maps and filters that are particularly simple).

Apple can and will change the parameter types of Swift that are converted by objective-c frameworks. For example, options are removed or become auto-expanded, and so on. We should intentionally specify your options and rely on Swift to infer the type, reducing the risk of a program interruption in this case.

You should always specify the return type in moderation. For example, this parameter list is obviously overly redundant:

Dispatch_async (queue) {(), Void in print ("Fired.")}

6. Constants

At the time of type definition, constants should be declared as static in the type. For example:

struct Physicsmodel {static var speedoflightinavacuum = 299_792_458}class Spaceship {

static let TopSpeed = physicsmodel.speedoflightinavacuum var speed:double func fullspeedahead () {speed = SPACESHIP.TOPSP Eed}}

Using the static modifier constants allows them to be referenced without having to instantiate the type.

In addition to the Singleton, you should try to avoid generating global constants.

7. computed Type attributes (Computed properties)

When you only need to inherit the Getter method, return the simple Computed property. For example, you should do this:

Class Example {var age:uint32 {return arc4random ()}}

Instead of:

Class Example {var age:uint32 {get {return arc4random ()}}}

If you add set or Didset to a property, you should provide a GET method to display it.

Class Person {var age:int {get {return Int (Arc4random ()}} set {print ("This ' s not your age.")}}}

8. instance conversion (converting Instances)

When creating code to convert from one type to another init () method:

Extension NSColor {convenience init (_ Mood:mood) {Super.init (Color:NSColor.blueColor)}}

In the Swift standard library, for converting instances of one type to another, it now seems that the Init method is a more preferred way.

The "to" method is another reasonable technique (although you should follow Apple's guidance to use the Init method):

struct Mood {func tocolor (), NSColor {return Nscolor.bluecolor ()}}

And you might try to use a getter, for example:

struct Mood {var color:nscolor {return Nscolor.bluecolor ()}}

Getters is usually limited by the components that should return an acceptable type. For example, returning an instance of circle is ideal for getter use, but converting a circle to Cgpath is best used with the "to" function or the init () extension on Cgpath.

Next: iOS Development--17 Swift Best Practices specification (bottom line)

For more information on iOS development, please visit the China Soft International Education Group Technical Knowledge Base!

Getting Started with iOS development-17 Swift Best Practices Specification (top)

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.