Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了What’s New in Swift 2大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

We’ll have plenty of written and video Swift 2 tutorials for you soon, but in the meantime I wanted to highlight the most exciTing changes so you can be prepared for the great migration to Swift 2 in

We’ll have plenty of written and video Swift 2 tutorials for you soon,but in the meantime I wanted to highlight the most exciTing changes so you can be prepared for the great migration to Swift 2 in the fall.

@H_675_16@ Error Handling

As Ray mentioned in hisWWDC 2015 Initial Impressionspost,error handling has been revamped in Swift 2. Instead ofNSErrorobjects and double pointers,we’re moving to a new system that looks SIMILAR TO exception handling.

You may be familiar with code like this:

@H_403_15@if drinkWithError(nil) { print("Could not drink beer! :[") return }

Generally in Cocoa,you pass in a reference to anNSErrorobject (aninoutparameter in Swift) and then the method will assign the variable if there was a problem. However,the problem is that you can passnilhere to completely ignore the error; or,you can pass in theNSErrorbut then never check it.

Swift 2 adds additional safety to your error checking. You use thethrowskeyword to specify which functions and methods Could throw an error. Then you have thedo,try,andcatchkeywords for when you call something that Could throw:

@H_403_15@// 1 enum DrinkError: ErrorType case NoBeerRemainingError } // 2 func drinkWithError() throws if beer.isAvailable{ // party! } else // 3 throw DrinkError.NoBeerRemainingError } } func tryToDrink{ // 4 do { try drinkWithError) } catch { ) return There are a few things to highlight here:

  1. To create an error to throw,simply create anenumthat derives fromErrorType.
  2. You need to use thethrowskeyword to mark any function that can throw an error.
  3. This throws an error,which will be caught in section 4.
  4. Instead oftryblocks,which might be familiar from other languages,you wrap any code that can throw an error in adoblock. Then,you add thetrykeyword to each function call that Could throw an error.

The new Syntax is pretty lightweight and readable. Any API that currently usesNSErrorNow uses this system,so we’ll be seeing a lot of it!

Binding

With Swift 1.2,we lost the “pyramid of doom” and gained the ability to test binding multiple optionals in one line:

@H_403_15@if let pants = pants,frog = frog // good stuff here! That works just fine,but the issue for some people is that the “preferred” code path where all the optionals have some value is indented. That means you need to keep looking inside indented code blocks for the mainline part of your code,while the error conditions are outside.

If only there were some way to check that some of the optionals don’t have a value,and then exit early! That’s exactly what Swift 2 offers with its guard statement:

@H_403_15@guard = frog // sorry,no frog pants here :[ // at this point,frog and pants are both unwrapped and bound!

Usingguard@H_191_20@means you can perform the optional binding (or any other operation,really) and provide a code block in theelseto run if the condition fails. Then,you can conTinue on –in this case,the optionalsfrogandpantsare Now bound and are no longer optionals in scope.

This should make for much clearer code sinceguardlets you specify the state you’re actually expecTing rather than checking for the error case.

@H_450_236@Note:If your’e still confused about why the guardstatement is more useful than if-elsestatements alone,check out Swift team member Eric Cerney‘s post on the Swift guard statement.

Protocol Extensions

Object-oriented? Functional? There’s one more to add to the front of the line of what Swift is: a protocol-oriented progrAMMing language!

In Swift 1,protocols were like interfaces to specify a set of properties and methods that a class,struct,or enum would then conform to.

Now in Swift 2,you can extend protocols and add default implementations for properties and methods. You can already do this with classes and structs — adding new methods toStringorArray,for example — but adding these to protocols Now gives you a much wider reach.

@H_403_15@extension CustomStringConvertible var shoutyDescription: String return "\(self.description.uppercaseString)!!!" let greeTings = ["Hello","Hi",26)">"Yo yo yo"
] // prints ["Hello","Hi","Yo yo yo"] \(greeTings.description)"
) // prints [HelLO,HI,YO YO YO]!!! \(greeTings.shoutyDescription)")

Note that thePrintableprotocol is Now calledCustomStringConvertible,which most Foundation objects conform to. With protocol extensions,you can extend wide swaths of the system with your own custom functionality. And rather than adding bits of custom code to many classes and structs and enums,you can write one general implementation and have it apply across a set of types.

The Swift team has been busy doing this already —if you’ve ever used@H_211_57@maporfilterin Swift,you may have thought they would do better as@H_261_82@methodsrather than as global functions. Thanks to the power of protocol extensions,there are a new set of methods on collection types such as@H_211_57@map,55)">filter,55)">indexOf,and more!

@H_403_15@let numbers [1,5,217)">6,217)">10,217)">16,217)">42,217)">45// Swift 1 findfilter@H_865_89@map(numbers,{ $0 * 2}),0)">% 3 == 90// Swift 2 numbers.@H_406_33@map 2 }.filter }.indexOf() // returns 2

Thanks to protocol confoRMANce,your Swift 2 code can be more concise and readable. With the Swift 1 version,you need to look at the calls inside out to understand what’s going on; in the Swift 2 version,the chain of functions is clear.

You’re also Leveraging the power of protocol-oriented progrAMMing —check out theWWDC session on this topicand keep an eye out for future tutorials and articles here on the site!

Grab Bag

There were a ton of things Announced throughout all the sessions,so I want to highlight a few more quick things:

  • @H_450_236@Objective-C generics– Apple has already started AnnotaTing all their Objective-C code so that types in Swift get the correct kind of optionality. That work conTinues with Objective-C generics,which will give Swift developers better type hinTing. If you’re expecTing a set ofUITouchobjects or an array of Strings,that’s exactly what you’ll get rather than a collection ofAnyObjects.
  • @H_450_236@Renamed Syntaxprintlnhas left us after only a year; Now it’s plain oldprintwhich Now has a default second Boolean argument set totrueon whether to print a newline or not. With thedokeyword focused on scope for error handling,do-while loops are Now@H_450_236@repeat-while. Similarly,there are many changes to protocol names such asPrintablebecomingCustomStringConvertible.
  • @H_450_236@migrator– With all these small Syntax changes,how are you going to get your codebase up to date? The Swift 1-to-2 migrator will come to the rescue and Help bring things up to the latest standards and Syntax changes. The migrator is even smart enough to update your code to use the new error handling and update your docblock comments to the new style of formatTing!
  • @H_450_236@open source@H_450_236@!–The big news for the nerds is that Swift is going open source when Swift 2 is released in the fall. Likely this will lead to Swift being used for more than just iOS development,which makes it even more important to learn. Plus,it will be a great opportunity to get a look under the hood and even to contribute BACk and get your name in the Swift compiler commit history. ;]

大佬总结

以上是大佬教程为你收集整理的What’s New in Swift 2全部内容,希望文章能够帮你解决What’s New in Swift 2所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:newsswift