Getting Started with iOS development-17 Swift best Practices (bottom line)

Source: Internet
Author: User

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

Take the above: Getting Started with iOS development--17 Swift Best Practices (top)

9. Single case (singletons)

In Swift, the singleton is simple:

Class Controversymanager {static Let sharedinstance = Controversymanager ()}

Swift's runtime guarantees the creation of a singleton and is accessed in a thread-safe manner.

A singleton usually only needs to access the static properties of "Sharedinstance" unless you have a compelling reason to rename it. Note that you do not use static functions or global functions to access your singleton.

(Because a single case in Swift is too simple, and the ongoing naming has taken too much of your time, you should have more time to complain about why the Singleton is an anti-pattern design, but avoid spending too much time, and your partner will thank you.) )

  10. Using extensions to organize your code

Extensions should be used to organize your code.

The minor methods and properties of an instance should be moved into the extension. Note that not all attribute types are now supported to move to the extension, and in order to do the best, you should use extensions in this restriction.

You should use extensions to help organize your instance definitions. A good example of this is that a View Controller Inherits table view data source and delegate protocols. To minimize the code in table view, the data source and delegate methods are integrated into the extension to accommodate the corresponding protocol.

In a single source file, add some definitions to the extension when you think you can best organize your code. Do not worry about adding extensions to the methods in the main class or to the methods in the struct that point to methods and property definitions. As long as all the files are in a Swift file, that's fine.

Conversely, the instance definition of main should not point to an element that defines an extension beyond the scope of the main Swift file.

  11. Chain-Type Setters

For simple setters properties, do not use the chained setters method as a convenient alternative.

The right approach:

Instance.foo = 42instance.bar = "Xyzzy"

The wrong approach:

Instance.setfoo (Setbar) ("Xyzzy")

Compared to chained setters, the traditional setters is simpler and does not require too much formulation.

  12. Error Handling

The do/try/catch mechanism of Swift 2.0 is very good.

  13. Avoid using try!

In general, use the following notation:

Do {try Somethingthatmightthrow ()}catch {fatalerror ("Something bad happened.")}

Instead of:

try! Somethingthatmightthrow ()

Even though this form is particularly verbose, it provides context so that other developers can examine the code.

Before a more detailed error-handling strategy comes out, if the try! As a temporary error handling is no problem. But it is advisable to check your code periodically to find out any illegal try! that might have escaped your code check.

  14. Avoid using try?

Try is used to "suppress" errors, and the try is useful only if you are sure that you do not care about the generation of the error. In general, you should catch an error and print at least one error.

  15. Premature return to &guards

If possible, use the guard declaration to handle premature returns or other exits (for example, fatal errors or thorwn errors).

The correct wording:

Guard Let Safevalue = Criticalvalue else {fatalerror ("Criticalvalue cannot is nil here")}somenecessaryoperation (Safevalu E

The wrong wording:

If let Safevalue = criticalvalue {somenecessaryoperation (safevalue)} else {fatalerror ("Criticalvalue cannot is nil here" )}

Or:

if Criticalvalue = = nil {fatalerror ("Criticalvalue cannot is nil here")}somenecessaryoperation (criticalvalue!)

This flatten code otherwise enters an if let block and exits prematurely in the context of the relevant environment, rather than entering the else code block.

Even when you do not capture a value (guard let), this pattern also forces premature exit during compilation. In the second if example, although the code is flattend like a guard, a destructive error or other process that returns some non-exiting (or an illegal state based on an exact instance) will cause crash. When a premature exit occurs, the Guard statement will detect the error in time and remove it from the else block.

  "Early" Access control

Even if your code is not separated into separate modules, you should always consider access control. Marking a definition as private or internal is equivalent to a lightweight document for your code. Everyone who reads the code will know that this element cannot be "touched". Conversely, defining a public is equivalent to inviting other code to access the element. Instead of relying on Swift's default access control level, we'd better show it. (internal)

If your code base expands in the future, it may be decomposed into submodules. Doing so will make it easier and faster to have a code base that has been decorated with access control information.

  17. Restrictive access Control

Generally speaking, when adding access control to your code, it's best to have detailed restrictions. Here, using private is more meaningful than internal, and using internal is obviously better than public. (Note: internal is the default).

If necessary, it is very easy to make the access control of the code more open (along the way: "Private" to "internal" to "public"). Overly open access control code may not be appropriate for use by other code. Code with sufficient limitations can detect inappropriate and incorrect use and provide a better interface. An example is a type that exposes a internal cache publicly.

Furthermore, restricted access to the code limits the "surface area of exposure" and allows the code to refactor in the case of smaller effects on other code. Other technologies such as: Protocol Driven development can also play the same role.

Learn more about iOS development Welcome to China Soft International education Group Technical Knowledge Base

Getting Started with iOS development-17 Swift best Practices (bottom line)

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.