Swift 2.0

Source: Internet
Author: User
Tags try catch

Swift 2.0

In a twinkling of an eye, Swift is more than one year old. This new language, featuring fashionable syntax, type security, and faster execution speed, has gradually penetrated into the hearts of developers. I also love this new programming language. On October 11, June this year, the annual WWDC Conference arrived as scheduled. At the Conference, Apple released Swift 2.0, introducing many new features to help developers build applications faster and simpler. I will also talk about the new features worth your attention in Swift 2.0.

Guard statement

The guard statement is similar to the if statement. It determines what to execute next Based on the Boolean value of the expression after the keyword. However, unlike the if statement, the guard statement only has one code block, unlike the if statement, which can have multiple if else code blocks. So what is the role of the guard statement? As the name suggests, it is the guardian. When the Boolean value of the following expression is determined by the guard statement as false, the code in the subsequent code block will be executed. If it is true, the entire guard statement will be skipped. Let's take an example.

Taking this year's college entrance examination as an example, we usually check the ID card and admission ticket when entering the test room. We will write this method:

The first guard statement in the above code is used to check the ID card. If the ID card is not found, that is, when the expression is false, execute the code in braces and return. The second guard statement checks the admission ticket.

If the two certificates are complete, execute the last print statement. The code in the braces of the two guard statements above will not be executed because the Boolean values of their expressions are true.

It is worth noting that id and examNumber can be used outside the guard statement. That is to say, after guard verifies its expression, id and examNumber can be used in the whole method scope, and it is after unpacking.

We are writing a similar method using an if else statement.

We can see that the method implemented with if else is obviously less accurate than that implemented by guard. In addition, the scope of id and examNumber is limited to the first braces of if. An error will be reported if the scope is exceeded.

From the two small examples above, it is not difficult to see that the guard statement is like a competent guard, which checks every layer to prevent anything that is not allowed to happen, and makes the code more readable and very good.

Exception Handling

In the Swift 1.0 era, there is no exception handling and throw mechanism. To handle exceptions, either use the if else statement or switch statement to judge and process the exceptions, or use a callback function in the form of a closure, then, use NSError for processing. None of the above methods can process exceptions like the try catch exception Control statement in Java, and reduce the readability of the Code. When Swift 2.0 arrives, everything will be different.

In Swift 2.0, Apple provides an exception control processing mechanism consisting of five keywords throws, throw, try, do, and catch. The following is an example of how to use it. I use a mobile phone to brush the circle of friends.

First, we need to define the exception enumeration. In Swift 2.0, Apple provides the ErrorType protocol and the custom exception enumeration follows:



We have defined the 'wechaterror.

Then define a method to check whether the image can be refreshed: checkIsWechatOk ():


 

Note that there is a throws keyword after the method name, which means that the exception generated by this method is thrown up the layer. In the method body, use the guard statement to determine various states, and then use the throw keyword to throw the corresponding exception. Then we define the method for refreshing:

In the preceding code example, the try keyword is used before checking whether the method can be flushed to allow the method to throw an exception. Then, the do catch control statement is used to capture the thrown exception, then perform related logic processing.

This exception handling mechanism makes Swift more comprehensive and secure, and improves the readability of the Code.

Protocol Extension

In the Swift 1.0 era, protocols are basically similar to an interface and define several attributes and methods for class, struct, and enumeration to follow and implement.

In Swift 2.0, attributes or methods of the Protocol can be extended, similar to the extension class and struct. This opens the chapter of protocol-oriented programming.

In Swift, most basic objects follow the CustomStringConvertible protocol, such as Array and Dictionary (Printable protocol in Swift 1.0). This Protocol defines the description method for printing objects using the print method. Now we can extend a method for this Protocol to print the upper-case content:

In the Swfit 1.0 era, to achieve the effects of the above examples, we need to expand the Array and Dictionary respectively, so protocol extension greatly improves our programming efficiency, it also makes the code simpler and easier to read.

Print statement changes

In Swift1, there are two methods to print statements on the console: 'println () 'and 'print ()'. The former is line feed printing, and the latter is line feed printing. In Swift2, 'println () 'has become a combination of them. If you want to print a line feed, you need to write it like this:


 

Available check

As iOS developers, everyone wants to use the latest iOS Api for development, saving time and effort. But it is often counterproductive, because we often need to adapt to the old version of iOS, this will face a problem, some new features or some classes cannot be used in the old version of iOS, therefore, the iOS version is often judged during the encoding process, just like this:

The above is only one method. Before Swift 2.0, there is no standard mode or mechanism to help developers determine the iOS version, and it is prone to omissions. After the arrival of Swift 2.0, we had a standard way to do this:


 

This feature makes us so happy.

Do-while statement rename

The classic do-while statement is renamed to repeat-while:

I personally feel more intuitive.

Defer keyword

In some languages, there are control statements such as try/finally, such as Java. This type of statement allows us to execute the code that must be executed in the finally code block, regardless of the past. In Swift 2.0, Apple provides the defer keyword, allowing us to achieve the same effect.

The preceding example shows that after "CheckPoint 2" is printed, "Clean up here" is not printed, but "CheckPoint 3". This is the role of defer, it delays print ("Clean up here. Let's take a look at an I/O example:

 

The preceding example is a pseudo-code for an I/O operation. If the obtained ioStatus is normal, this method is normal. If the ioStatus obtained is error, the return operation will be caught by the guard statement, so that closeFile (file) will never be executed, and a serious Bug will be generated. Let's take a look at how to use defer to solve this problem:

We put closeFile (file) in the defer code block, so that even if ioStatus is error, the code in defer will be executed before the return is executed, so that no matter what happens, close the file. Defer is another feature that ensures the robustness of our code. I like it very much. Of course, the new features in Swift 2.0 are not limited to the above, but the full picture can be seen!


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.