What's new in Swift 2.2

What's new in Swift 2.2,第1张

概述From https://www.hackingwithswift.com/swift2-2 Swift 2.2 is almost here, and cleans up a numberof quirks, adds some missing features, and deprecates – perhaps controversially – some language features.

Fromhttps://www.Hackingwithswift.com/swift2-2

Swift 2.2 is almost here,and cleans up a numberof quirks,adds some missing features,and deprecates – perhaps controversially –some language features. This article goes over all the major changes,along with several minor ones,and gives you practical code examples so you can get up and running straight away.

If you liked this article,you might also want to read:

What's new in Swift 2.0? What's new in iOS 9? My free Swift tutorial series Pre-order Pro Swift for just $20! Watch my Swift 2.2 vIDeo

I made a vIDeo going over the key new features in Swift 2.2. You can read the original article below,or watch this vIDeo for my lightning summary. Feedback?Find me on Twitter @twostraws.

++ and -- are deprecated

Swift 2.2 formally deprecates the++and--operators,which means they still work but you'll get a warning when you use them. Deprecation is usually a first step towards removing something entirely,and in this case both of these operators will be removed in Swift 3.0.

In their place,you need to use+= 1and-= 1instead. These operators have been there all along,and are not going away.

You might wonder why two long-standing operators are being removed,particularly when they exist in C,C#,Java,and – critically to its "joke" –C++. There are several answers,not least:

Writing++rather than+= 1is hardly a dramatic time saving Although it's easy once you kNow it,++doesn't have an obvIoUs meaning to people learning Swift,whereas+=at least reads as "add and assign." C-style loops – one of the most common situations where--were used – have also been deprecated,which brings me on to my next point… Traditional C-style for loops are deprecated

Yes,you read that correctly: loops like the below will soon be removed entirely from Swift:

for var i = 1; i <= 10; i += 1 {    print("\(i) green bottles")}

These are called C-style for loops because they have long been a feature of C-like languages,and conceptually even pre-date C by quite a long way.

Although Swift is (just about!) a C-like language,it has a number of newer,smarter alternatives to the Traditional for loop. The result: this construct has been deprecated in Swift 2.2 and will be removed "in a future version of Swift."

Note: the current deprecation warning does not say it's removed in Swift 3.0,although I SUSPECT it will be.

To replace these old for loops,use one of the many alternatives. For example,the "green bottles" code above Could be rewritten to loop over a range,like this:

for i in 1...10 {    print("\(i) green bottles")}

Remember,though,that it's a bad IDea to create a range where the start is higher than the end: your code will compile,but it will crash at runtime. So,rather than writing this:

for i in 10...1 {    print("\(i) green bottles")}

…you should write this instead:

for i in (1...10).reverse() {    print("\(i) green bottles")}

Another alternative is just to use regular fast enumeration over an array of items,245);">var array = [1,2,3,4,5,6,7,8,9,10]for number in array { print("\(number) green bottles")}

Although if you want to be technically correct (also kNown as "the best kind of correct") you would write such a beast like this:

var array = Array(1...10)for number in array {    print("\(number) green bottles")}
Arrays and other slice types Now have removeFirst()

TheremoveLast()method has always been helpful when working with arrays,but until Now it's been missing a counterpart to remove items from the start of an array.

Well,Swift 2.2 is here to rescue you with the addition of theremoveFirst()method. This removes the first element in an array,and returns it to you.

Looking back to the green bottles code above,you'll notice two quirks: first,I was usingvarrather thanlet,and second it was printing the grammatically incorrect message "1 green bottles".

Neither of these are a mistake,because I'm going to use them to demonstrateremoveFirst():

var array = Array(1...10)array.removeFirst()for number in array {    print("\(number) green bottles")}

Warning:whereasremoveLast()has an optional equivalent,244);">popLast(),there is no optional equivalent forremoveFirst(). This means if you call it on an empty array,your code will crash.

You can Now compare tuples (within reason)

A tuple is simply a comma-separated List of values,where each value may or may not be named. For example:

let singer = ("Taylor","Swift")let alIEn = ("Justin","BIEber")

In older versions of Swift,you Couldn't compare two tuples without writing some unwIEldy code like this:

func ==        (t1: (T,T),t2: (T,T)) -> Bool {    return t1.0 == t2.0 && t1.1 == t2.1}  

It's not very user-frIEndly to require that kind of boilerplate code,and of course it would only work for tuples that have exactly two elements. In Swift 2.2,you no longer need to write that code because tuples can be compared directly:

 

Swift 2.2's automatic tuple comparison works with tuples with two elements just like the function we wrote,but it also works with tuples of other sizes – up to arity 6,which means a tuple that contains six elements.

(In case you were wondering: "arity" is pronounced like "arrity",but "tuple" is pronounced any number of ways: "toople","tyoople" and "tupple" are all common.)

There are two reasons why Swift's tuple comparisons work only up to arity 6 (rather than arity 6 million). First,each extra comparison requires more code insIDe the Swift standard library. Second,using tuples that big is probably a code smell – switch to a struct instead.

You can see how tuple comparison works by changing our two tuples like this:

Be prepared for a very long error message from Xcode,but the interesting part comes near the end:

note: overloads for '==' exist with these partially matching parameter Lists: ......((A,B),(A,B)),((A,B,C),C)),C,D),D)),D,E),E)),E,F),F))

As you can see,Swift literally has functions to compare tuples all the way up to(A,F),which ought to be more than enough.

Tuple splat Syntax is deprecated

Staying with tuples for a moment longer: another feature that has been deprecated is one that has been part of Swift since 2010 (yes,years before it launched). It's been named "the tuple splat",and not many people were using it. It's partly for that reason – although mainly because it introduces all sorts of ambiguitIEs when reading code – that this Syntax is being deprecated.

In case you were curIoUs – and let's face it,you probably are – here's an example of tuple splat Syntax in action:

func describePerson(name: String,age: Int) {    print("\(name) is \(age) years old")}let person = ("Taylor Swift",age: 26)describePerson(person)

But remember: don't grow too fond of your new kNowledge,because tuple splats are deprecated in Swift 2.2 and will be removed entirely in a later version.

More keywords can be used as argument labels

Argument labels are a core feature of Swift,and let us write code like this:

for i in 1.strIDe(through: 9,by: 2) {    print(i)}

Without thethroughorbylabels,this code would lose its self-documenting nature: what do the 9 and 2 do in1.strIDe(9,2)? In this example,Swift also uses the argument labels to distinguish1.strIDe(through: 9,by: 2)from1.strIDe(to: 9,by: 2),which produces different results.

As of Swift 2.2,you can Now use a varIEty of language keywords as these argument labels. You might wonder why this would be a good thing,but consIDer this code:

func printGreeting(name: String,repeat repeatCount: Int) {    for _ in 0 ..< repeatCount {        print(name)    }}printGreeting("Taylor",repeat: 5)

That usesrepeatas an argument label,which makes sense because the function will print a string a number of times. Becauserepeatis a keyword,this code would not work before Swift 2.2 – you would need to write`repeat`instead,which is unpleasant.

Note that there are still some keywords that may not be used,specificallyvar,244);">letandinout.

var parameters have been deprecated

Another deprecation,but again with good reason:varparameters are deprecated because they offer only marginal usefulness,and are frequently confused withinout. These things are so sneaky I Couldn't resist adding one to mySwift language tests,although I will probably have removed them by the time you read this!

To give you an example,here is theprintGreeting()function modifIEd to usevar:

func printGreeting(var name: String,repeat repeatCount: Int) {    name = name.uppercaseString    for _ in 0 ..< repeatCount {        print(name)    }}printGreeting("Taylor",sans-serif; Font-size: 16px; line-height: 28px;">The differences there are in the first two lines:nameis Nowvar name,andnamegets converted to uppercase so that "TAYLOR" is printed out five times.

varkeyword,244);">namewould have been a constant and so theuppercaseStringline would have Failed.

The difference betweenvarandinoutis subtle: usingvarlets you modify a parameter insIDe the function,244);">inoutcauses your changes to persist even after the function ends.

varis deprecated,and it's slated for removal in Swift 3.0. If this is something you were using,just create a variable copy of the parameter insIDe the method,repeat repeatCount: Int) { let uppername = name.uppercaseString for _ in 0 ..< repeatCount { print(uppername) }}printGreeting("Taylor",repeat: 5)

Renamed deBUG IDentifIErs: #line,#function,#file

Swift 2.1 and earlIEr used the "screaming snake case" symbols__file__,244);">__liNE__,244);">__ColUMN__,244);">__FUNCTION__,which automatically get replaced the compiler by the filename,line number,column number and function name where they appear.

In Swift 2.2,those old symbols have been replaced with#file,244);">#line,244);">#columnand#function,which will be familiar to you if you've already usedSwift 2.0's #availableto check for iOS features. As the official Swift revIEw says,it also introduces "a convention where # means invoke compiler substitution logic here."

Below I've modifIEd theprintGreeting()function so you can see both the old and new deBUG IDentifIErs in action:

For the sake of completion,I should add that you can also use#dsohandle,but if you kNow what dynamic shared object handles are you probably already spotted this change yourself!

StringifIEd selectors are deprecated

One unwelcome quirk of Swift before 2.2 was that selectors Could be written as strings,245);">navigationItem.rightbarbuttonItem = UIbarbuttonItem(Title: "Tap!",style: .Plain,target: self,action: "buttonTaped")

If you look closely,I wrote"buttonTaped"rather than"buttonTapped",but Xcode wasn't able to notify me of my mistake if either of those methods dIDn't exist.

This has been resolved as of Swift 2.2: using strings for selectors has been deprecated,and you should Now write#selector(buttonTapped)in that code above. If thebuttonTapped()method doesn't exist,you'll get a compile error – another whole class of BUGs eliminated at compile time!

Compile-time Swift version checking

Swift 2.2 adds a new build configuration option that makes it easy to combine code code written in versions of Swift into a single file. This might seem unnecessary,but spare a thought to people who write librarIEs in Swift: do they target Swift 2.2 and hope everyone is using it,or target Swift 2.0 and hope users can upgrade using Xcode?

Using the new build option lets you write two different flavours of Swift,and the correct one will be compiled depending on the version of the Swift compiler.

For example:

#if swift(>=2.2)print("Running Swift 2.2 or later")#elseprint("Running Swift 2.1 or earlIEr")#endif

Just like the existing#if os()build option,this adjusts what code is produced by the compiler: if you're using a Swift 2.2 compiler,the secondprint()line won't even be seen. This means you can use utter gibberish if you want:

#if swift(>=2.2)print("Running Swift 2.2 or later")#elseTHIS WILL COMPILE JUST FINE IF YOU'REUSING A SWIFT 2.2 COMPILER BECAUSETHIS BIT IS COMPLETELY IGnorED!#endif
New documentation keywords: recommended,recommendedover,and keyword

Swift supports Markdown-formatted comments to add Metadata to your code,so you can write things like this:

/**Say hello to a specific person- parameters:- name: The name of the person to greet- returns: absolutely nothing- authors:Paul HudsonBilbo Baggins- BUG: This is a deeply dull function*/func sayHello(name: String) {    print("Hello,\(name)!")}sayHello("Bob")

This Metadata gets used in code completion ("Say hello to a specific person" gets shown as you type) and also in the quick help pane,which is where the other data is shown.

recommended,244);">recommendedover,244);">keyword. These appear to be designed to make code completion more useful by letting you specify which propertIEs and methods should return matches insIDe Xcode,but right Now it doesn't appear to be working so that's only a hunch.

When things do suddenly spring into life – soon,I hope! – you can use them like this:

/**Greets a named person- keyword: greeting- recommendedover: sayHellotopaul*/func sayHello(name: String) { }/**Always greets the same person- recommended: sayHello*/func sayHellotopaul() { }

recommendedlets you say "prefer this other method instead",244);">recommendedoverlets you say "prefer me over this other method."

like I saID,these don't appear to be functional in the current Xcode 7.3,but I filed a BUG with Apple in the hope of getting some clarity around what these do,and will update this page when I find out more.

On the plus sIDe,Xcode 7.3 does feature all-new code completion: you can Now type something like "strapp" to have "stringByAppendingString" highlighted in the code completion,or "uitavc" to have "UItableVIEwCell" highlighted. It will take a little thinking to rewire your brain to use these text shortcuts,but it does promise a significant speed up for your Coding.

总结

以上是内存溢出为你收集整理的What's new in Swift 2.2全部内容,希望文章能够帮你解决What's new in Swift 2.2所遇到的程序开发问题。

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1078152.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存