What are the new features of Swift 2

Source: Internet
Author: User

At WWDC we found that the swift team did not waste time in pointless places, but was committed to improving Swift 2.

We will write and record many tutorials for you on Swift 2, but in the meantime I would like to highlight the most exciting changes in Swift that will prepare you for moving to Swift 2 in the fall.

Error handling

As Ray mentions in the WWDC Initial impressions article, error handling has been improved in Swift 2. We have migrated to the new system just like exception handling, not nserror objects and double pointers.

You may be more familiar with the following code:

objective-c
1234 if drinkwitherror(nil) { Print(" Could not drink beer! :[") return }

Swift 2 Adds an additional layer of protection for error checking. You can use the throws keyword to specify that the function and method can throw an error. Then when you call something, you can use do, try, and catch multiple keywords to catch and handle errors.

Typically in cocoa, you pass in a reference to a Nserror object (a inout parameter is in Swift), and the method assigns a value to the error variable. The problem is that you can pass in a nil here to completely ignore the error, or you can pass in Nserror but never check it.

objective-c
123456789101112131415161718192021222324 //1enum drinkerror: ErrorType { Case nobeerremainingerror }//2func drinkwitherror() throws { if beer. IsAvailable() { //party! } else { //3 throw drinkerror. Nobeerremainingerror   }}func trytodrink() { //4 Do { try drinkwitherror() } catch { Print(" Could not drink beer! :[") return   }}

Here are a few things to emphasize:

    1. In order to create an error can be thrown, just create an enum that inherits ErrorType.
    2. You need to use the throws keyword to flag any function that can throw an error.
    3. This throws an error and it will be captured in section 4.
    4. You include in a Do block any code that can throw an error, rather than a try block similar to another language. Then, you add a try keyword to the front of the function being called, and the function can throw an error.

The new syntax is very concise and easy to read. Any API that is currently using Nserror will use this method of error handling.

Binding

In Swift 1.2, we lost the doom of the pyramids and were able to test multiple bindings in one line of code optionals:

objective-c
123 if let pants = pants, frog = frog { /c16> //Good Stuff here! }

It's hard to work, but it's a problem for some people to indent the "preferred" code path for values that are nested with a lot of optionals to access. This means that you need to drill down into the block of code that indents the main line, while the error condition is outside.

If there are some ways to check for some optionals that have no value, then exit early. This is the guard statement provided by Swift 2:

objective-c
123456 guard let pants = pants frog = frog else { /span>   //Sorry, no frog pants here: [   return }  //at this point, frog and pants is both unwrapped and Boun d!

Using guard means that you can perform optional binding (or other operations) and provide a block of code in the else run if the condition fails. Then, you can continue to execute. In this case, optionals frog and pants are unwrap within the scope.

Use Guard to specify something that you want to get state instead of checking for error conditions to make your code more concise.

Note: If you still don't understand why using guard statements is more useful than if-else statements, check out the Swift team Eric Cerney's post at Swift Guard statement.

Protocol Extensions

Object-oriented programming? Functional programming? Swift is actually a protocol-oriented programming language!

In Swift 1, the protocol is like an interface where you can specify properties and methods, and then classes, structs, or enumerations follow it.

Now in Swift 2, you can extend the protocol and add default implementations to properties and methods. You have previously been able to add new methods to a string or array in a class or struct, but now you can add these to the protocol, which allows you to apply it more broadly.

objective-c
12345678910111213 extension customstringconvertible { var shoutydescription: String { return " \(self. Description. Uppercasestring)!! ! "   }}LetGreetings = ["hello", " hi", " yo yo Yo"" //Prints [" Hello", " Hi", " Yo yo Yo"]Print(" \(greetings. Description)") //Prints [HELLO, HI, yo yo yo]!!!Print(" \(greetings. Shoutydescription)")

Note The printable protocol is now named Customstringconvertible, and most of the foundation objects follow the printable protocol. With the protocol extension, you can extend the system with custom functionality. Rather than adding a small amount of custom code to many classes, structs, and enumerations, you can write a generic implementation and apply it to different data types.

The swift team is already busy doing this – if you have already used map or filter in Swift, you might also think that it is better to use them in a way than global functions. Thanks to the powerful protocol extensions, there have been a number of new methods added to the collection type, such as: Map,filter,indexof and more!

objective-c
1234567 et numbers = [1, 5, 6, ten, 16 , (a ) //Swift 1Find(Filter(Map(Numbers, { $0 * 2}), { $0 % 3 = = 0 }) //Swift 2Numbers.Map { $0 * 2 }. Filter { $0 % 3 == 0 }. Indexof (90 Span class= "Crayon-c" >//returns 2

Thanks to protocol consistency, your Swift 2 code will become more concise and readable. In the Swift 1 release, you need to look inside the calling function to understand how it works; in the Swfit 2 version, the function chain becomes clear.

If you plan to use protocol-oriented programming – check out the WWDC session on this topic and watch the tutorials and articles for this site.

Summary

There are a lot of things to be published in the WWDC conference, so I want to highlight a few important things:

    • The objective-c generic –apple has started labeling all objective-c code so that the swift type can obtain the correct type of optional. Working with Objective-c Generics also works well, giving swift developers a better type hint. If you want to have some Uitouch objects or array of strings, you'll get what you want instead of some anyobjects.
    • Renaming syntax –println has been away from us for a year; now it's plain old print, and now it has a second parameter whose default value is set to true to decide whether to wrap. The Do keyword is primarily used for error handling, and the Do-while loop is now using Repeat-while. Similarly, a lot of protocol names have changed, for example: Printable changed to customstringconvertible.
    • Migrator– has a lot of small grammatical changes, how do you make your code up to date? Swift 1-to-2 Migrator will turn code into the newest standard and change the syntax. This migrator smart to be able to update your code with new error handling, and update block annotations to new formatting styles!
    • Open source! – One of the big news for the code farmer is that Swift will open source in the autumn when Swift 2 is released! This means that you can not only use it for iOS development, but more importantly to learn its source code. Not only that, it would be a good opportunity to delve into the source code, even contribute code for the project, and then leave your name in the Swift compiler commit history.
Next

This is just some simple example of all the publishing features; For more information, see WWDC session videos and the updated Swift programming Language book

If there are other people who remember that there are many changes between Swift's first beta and release 1.0, there will definitely be more features coming up in the future. Our team will continue to focus on all the updates and dig into exciting changes, so keep a close eye on tutorials, books and videos.

Which part of Swift 2 is most exciting to you? Which part do you want us to report in the first time? Let us know in the comments below!

What are the new features of Swift 2

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.