What’s New in Swift 2
2015-08-05 18:13
671 查看
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.
As Ray mentioned in his WWDC
2015 Initial Impressions post, error handling has been revamped in Swift 2. Instead of
and double pointers, we’re moving to a new system that looks similar to exception handling.
You may be familiar with code like this:
Generally in Cocoa, you pass in a reference to an
(an
will assign the variable if there was a problem. However, the problem is that you can pass
to completely ignore the error; or, you can pass in the
then never check it.
Swift 2 adds additional safety to your error checking. You use the
to specify which functions and methods could throw an error. Then you have the
and
that could throw:
There are a few things to highlight here:
To create an error to throw, simply create an
derives from
You need to use the
function that can throw an error.
This throws an error, which will be caught in section 4.
Instead of
from other languages, you wrap any code that can throw an error in a
Then, you add the
call that could throw an error.
The new syntax is pretty lightweight and readable. Any API that currently uses
uses this system, so we’ll be seeing a lot of it!
![](http://cdn4.raywenderlich.com/wp-content/uploads/2015/06/throw-all-the-things-415x320.jpg)
With Swift 1.2, we lost the “pyramid of doom” and gained the ability to test binding multiple optionals in one line:
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:
Using
binding (or any other operation, really) and provide a code block in the
run if the condition fails. Then, you can continue on – in this case, the optionals
now bound and are no longer optionals in scope.
This should make for much clearer code since
you specify the state you’re actually expecting rather than checking for the error case.
Note: If your’e still confused about why the
is more useful than
check out Swift team member Eric
Cerney‘s post on the Swift
guard statement.
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 to
for example — but adding these to protocols now gives you a much wider reach.
Note that the
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
Swift, you may have thought they would do better as methods rather than as global functions. Thanks to the power of protocol extensions, there are a new set of methods on collection types such as
and more!
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 the WWDC
session on this topic and keep an eye out for future tutorials and articles here on the site!
There were a ton of things announced throughout all the sessions, so I want to highlight a few more quick things:
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 of
or an array of strings, that’s exactly what you’ll get rather than a collection of
Renamed syntax –
left us after only a year; now it’s plain old
now has a default second boolean argument set to
whether to print a newline or not. With the
focused on scope for error handling, do-while loops are now repeat-while. Similarly,
there are many changes to protocol names such as
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!
Open source! – 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. ;]
Error Handling
As Ray mentioned in his WWDC2015 Initial Impressions post, error handling has been revamped in Swift 2. Instead of
NSErrorobjects
and double pointers, we’re moving to a new system that looks similar to exception handling.
You may be familiar with code like this:
if drinkWithError(nil) { print("Could not drink beer! :[") return } |
NSErrorobject
(an
inoutparameter in Swift) and then the method
will assign the variable if there was a problem. However, the problem is that you can pass
nilhere
to completely ignore the error; or, you can pass in the
NSErrorbut
then never check it.
Swift 2 adds additional safety to your error checking. You use the
throwskeyword
to specify which functions and methods could throw an error. Then you have the
do,
try,
and
catchkeywords for when you call something
that could throw:
// 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 { print("Could not drink beer! :[") return } } |
To create an error to throw, simply create an
enumthat
derives from
ErrorType.
You need to use the
throwskeyword to mark any
function that can throw an error.
This throws an error, which will be caught in section 4.
Instead of
tryblocks, which might be familiar
from other languages, you wrap any code that can throw an error in a
doblock.
Then, you add the
trykeyword to each function
call that could throw an error.
The new syntax is pretty lightweight and readable. Any API that currently uses
NSErrornow
uses this system, so we’ll be seeing a lot of it!
![](http://cdn4.raywenderlich.com/wp-content/uploads/2015/06/throw-all-the-things-415x320.jpg)
Binding
With Swift 1.2, we lost the “pyramid of doom” and gained the ability to test binding multiple optionals in one line:if let pants = pants, frog = frog { // good stuff here! } |
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:
guard let pants = pants, frog = frog else { // sorry, no frog pants here :[ return } // at this point, frog and pants are both unwrapped and bound! |
guardmeans you can perform the optional
binding (or any other operation, really) and provide a code block in the
elseto
run if the condition fails. Then, you can continue on – in this case, the optionals
frogand
pantsare
now bound and are no longer optionals in scope.
This should make for much clearer code since
guardlets
you specify the state you’re actually expecting rather than checking for the error case.
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 to
Stringor
Array,
for example — but adding these to protocols now gives you a much wider reach.
extension CustomStringConvertible { var shoutyDescription: String { return "\(self.description.uppercaseString)!!!" } } let greetings = ["Hello", "Hi", "Yo yo yo"] // prints ["Hello", "Hi", "Yo yo yo"] print("\(greetings.description)") // prints [HELLO, HI, YO YO YO]!!! print("\(greetings.shoutyDescription)") |
Printableprotocol is now called
CustomStringConvertible,
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
mapor
filterin
Swift, you may have thought they would do better as methods rather than as global functions. Thanks to the power of protocol extensions, there are a new set of methods on collection types such as
map,
filter,
indexOf,
and more!
let numbers = [1, 5, 6, 10, 16, 42, 45] // Swift 1 find(filter(map(numbers, { $0 * 2}), { $0 % 3 == 0 }), 90) // Swift 2 numbers.map { $0 * 2 }.filter { $0 % 3 == 0 }.indexOf(90) // returns 2 |
You’re also leveraging the power of protocol-oriented programming — check out the WWDC
session on this topic and 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: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 of
UITouchobjects
or an array of strings, that’s exactly what you’ll get rather than a collection of
AnyObjects.
Renamed syntax –
printlnhas
left us after only a year; now it’s plain old
now has a default second boolean argument set to
trueon
whether to print a newline or not. With the
dokeyword
focused on scope for error handling, do-while loops are now repeat-while. Similarly,
there are many changes to protocol names such as
Printablebecoming
CustomStringConvertible.
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!
Open source! – 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. ;]
相关文章推荐
- Swift Guard Statement
- Swift2学习:Swift概览6-协议和扩展
- iPhone开发入门系列1(iOS8+Swift版)天天打靶APP学习03-06
- 在Swift创建CocoaPods
- ios swift下使用PPRevealSideViewController
- swift基础
- 【Swift】 GET&POST请求 网络缓存的简单处理
- 【Swift】 GET&POST请求 网络缓存的简单处理
- iPhone开发入门系列1(iOS8+Swift版)天天打靶APP学习01-02
- swift之函数式编程(五)
- Swift学习-页面跳转
- The Swift Programming Language 中文版 Swift2.0学习
- iOS编程——Swift使用resizableImageWithCapInsets来拉伸图片
- swift中tabbar切换页面动画
- iOS编程——Swift用代码为view添加各种圆角
- swift protocol
- Chapter 5:UIKit Dynamics - iOS 8 Swift Programming cookBook 读书笔记
- Swift:实例方法和类型方法
- Chapter 5:collection view - iOS 8 Swift Programming cookBook 读书笔记
- Swift iOS 文件操作:沙盒(SandBox)、程序包(NSBundle)