A probe into Swift 2.0

Source: Internet
Author: User
Tags try catch

In the blink of an eye, Swift is already one year old, this fresh, grammatical fashion, type security, execution speed of the language has gradually deepened the hearts of the vast number of developers. I am also very fond of this new programming language. In June of this year, the annual WWDC conference was scheduled, and Apple released Swift 2.0 at the conference, introducing many new features to help developers build applications faster and easier. I also say here the new features that are worth noticing in Swift 2.0.

Guard statement

A guard statement is a bit similar to an if statement, and is determined by the Boolean value of the expression after its keyword to decide what to do next. But unlike the IF statement, the guard statement will have only one block of code, unlike if the IF statement can have more than one block of code. So what is the role of the guard statement? As the name implies, is the Guardian. When the Guard statement determines that the subsequent expression has a Boolean value of false, then the code in the code block is executed, and if true, the entire guard statement is skipped, let's take a look at the example.

We take this year's college entrance examination as an example, when entering the examination room generally will check the ID card and the admission ticket, we write such a method:


The first guard statement in the preceding code is used to check the identity card, and if the ID is checked for no, that is, the expression is false, the code in curly braces is executed and returned. The second guard statement examines the admission ticket.

If both certificates are complete, the last print statement is executed, and the code in the two guard statement braces above does not execute, because the Boolean value of their expression is true.

It is worth noting that the IDs and Examnumber can be used outside of the guard statement, that is, after the guard has validated its expression, the IDs and Examnumber can be used in the scope of the entire method and after the unpacking.

We're writing a similar method with an if Else statement.


We can see that the method implemented with if else is obviously less precise than the guard implementation. And the scope of the ID and Examnumber is limited to the first curly brace of the IF, and the compiler will make an error if it goes beyond that scope.

  through these two small examples is not difficult to see, guard statements as a competent guard, layers of checks, to prevent all things not allowed to happen, and to make the code more readable, very good.

exception handling  

In the Swift 1.0 era there is no exception handling and throwing mechanism, if you want to handle the exception, either use the IF Else statement or the switch statement to determine the processing, or use a closed-form callback function processing, or use nserror processing. None of these methods can be as flowing, leisurely handling exceptions as the try catch exception control statement in Java, and will also reduce the readability of the code. When Swift 2.0 arrives, everything is different.

  in Swift 2.0, Apple provides an exception control processing mechanism that uses the five keywords of throws, throw, try, do, and catch. Let's take a look at how to use it, I use the mobile phone to brush the circle of friends for example.

  First we need to define an exception enumeration, in Swift 2.0 Apple provides the ErrorType protocol that requires our custom exception enumeration to follow:



We defined the error enumeration ' Wechaterror that caused the inability to brush.

Then define a method to check if it can be brushed Checkiswechatok ():



Note here that after the method name there is a throws keyword, meaning that the exception generated by the method is thrown to the upper layer. Use the Guard statement in the method body to judge various states, and then use the Throw keyword to throw the corresponding exception. Then we define the method of the brush:


In the preceding code example, first check whether the method can be brushed before using the Try keyword, which means that the method is allowed to throw an exception, and then use the Do catch control statement to catch the thrown exception, and then do the related logical processing.

This set of exception handling mechanisms makes swift more comprehensive and secure, and improves the readability of the code, which is great.

Protocol Extensions

In the Swift 1.0 era, the Protocol (PROTOCOL) basically resembles an interface, defining several properties and methods for classes, structs, enumerations to follow and implement.

In Swift 2.0, you can extend a property or method to a protocol, and the extension class is similar to a struct. This allows us to start a chapter in protocol-oriented programming.

In Swift, most of the base objects follow the Customstringconvertible protocol, such as the array, Dictionary (Printable protocol in Swift 1.0), which defines the description method, Prints the object for the Print method. Now let's extend a method to this protocol to print out uppercase content:


If in the Swfit 1.0 era, in order to achieve the results of the above example, then we need to expand the array, dictionary, so the extension of the protocol greatly improves our programming efficiency, but also makes the code more concise and easy to read.

  print statement change

  in Swift1, there are ' println () ' and ' Print () ' Two methods of printing statements in the console, the former is a newline print, the latter is a line printing. In Swift2, ' println () ' has become the past, replaced by the combination of the two. If you want to do a newline print, you need to write this now:



Available Check

As an iOS developer, everyone wants to use the latest version of iOS APIs for development, saving effort. But often backfired, because we often need to adapt to the old version of iOS, this will face a problem, some of the new features or some classes can not be used in the old version of iOS, so in the encoding process is often the version of iOS to judge, like this:


This is just one way, and there is no standard model or mechanism to help developers judge the iOS version before Swift 2.0, and is prone to omissions. After Swift 2.0 came, we had the standard way to do the work:



This feature makes us too happy.

Do-while Statement Renaming

The classic Do-while statement was renamed and changed to Repeat-while:

Personal feelings are more intuitive.

Defer keywords

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


The example above shows that after printing out "CheckPoint 2", it does not print "clean up here", but "CheckPoint 3", which is the function of defer, which has a print ("Clean up here") delay. Let's look at an example of I/O:


The above example is a pseudo-code for an I/O operation, if the obtained iostatus is normal, then the method is not a problem, if IoStatus is error, then the guard statement will catch the return operation, so CloseFile (file) Will never be executed, and a serious bug arises. Let's look at how to use defer to solve this problem:

We put CloseFile (file) in the defer code block so that even if the IoStatus is error, the code in defer is executed before the return, so that whatever happens, the file is closed at the end. Defer another feature that guarantees the robustness of our code, and I like it very much. The new features in Swift 2.0 are of course more than that, but the whole picture is visible!


A probe into Swift 2.0

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.