Swift 3.0一些Api变动

Swift 3.0一些Api变动,第1张

概述What's new in Swift 3.0 Swift 3.0 is changing pretty much everything, and your code will almost certainly refuse to build until you make the necessary changes. Seriously, if you thought the jump from What's new in Swift 3.0

Swift@H_419_9@3.0 is changingpretty much everything,and your code will almost certainly refuse to build until you make the necessary changes. SerIoUsly,if you thought the jump from Swift 1.2 to 2.0 was big,you ain't seen nothing yet.

In this article I'm going to explain some of the most important changes with as many code examples as I can,and hopefully this will give you some chance to be prepared to update your code when Swift 3.0 goes final. There are many more changes than the ones Listed below,but the changes below are the ones that are most likely to hit you.

If you liked this article,you might also enjoy these:


What's new in iOS 10? What's new in Swift 2.2? What's new in Swift 2.0? My free Swift tutorial series Buy my Pro Swift book Buy Objective-C for Swift Developers

ADVANCE WARNING #1:Swift 3.0 is still under development. This article will be updated as new changes are announced.

ADVANCE WARNING #2:There are lots and lots of changes,some of which might seem petty. However,the hope is that these changes are a once-off event that makes the language better for years to come,and it ought to mean that changes in later versions are significantly smaller.

ADVANCE WARNING #3:If you have not already read mywhat's new in Swift 2.2article,you should do so Now –everything that I saID was deprecated there has been removed,including ++,--,C-style for loops,tuple splat Syntax,and more.

All function parameters have labels unless you request otherwise

The way we call functions and methods already changed in Swift 2.0,but it's changing again and this time it's going to breakeverything. In Swift 2.x and earlIEr,method @R_404_6889@s dID not require a label for their first parameter,so the @R_404_6889@ of the first parameter was usually built into the method @R_404_6889@. For example:

<code  >@R_404_6889@s<span  >.</span><span  >indexOf</span><span  >(</span><span  >"Taylor"</span><span  >)</span><span  >"Taylor"</span><span  >.</span><span  >writetofile</span><span  >(</span><span  >"file@R_404_6889@"</span><span  >,</span> atomically<span  >:</span> <span  >true</span><span  >,</span> enCoding<span  >:</span> <span  >NSUTF8StringEnCoding</span><span  >)</span><span  >SKAction</span><span  >.</span><span  >rotateByAngle</span><span  >(</span><span  >CGfloat</span><span  >(</span><span  >M_PI_2</span><span  >)</span><span  >,</span> duration<span  >:</span> <span  >10</span><span  >)</span><span  >UIFont</span><span  >.</span><span  >preferredFontForTextStyle</span><span  >(</span><span  >UIFontTextStyleSubheadline</span><span  >)</span><span  >overrIDe</span> <span  >func</span> <span  >numberOfSectionsIntableVIEw</span><span  >(</span>tableVIEw<span  >:</span> <span  >UItableVIEw</span><span  >)</span> <span  >-</span><span  >></span> <span  >Int</span><span  >func</span> <span  >vIEwForZoomingInScrollVIEw</span><span  >(</span>scrollVIEw<span  >:</span> <span  >UIScrollVIEw</span><span  >)</span> <span  >-</span><span  >></span> <span  >UIVIEw</span><span  >?</span><span  >NSTimer</span><span  >.</span><span  >scheduledTimerWithTimeInterval</span><span  >(</span><span  >0.35</span><span  >,</span> target<span  >:</span> <span  >self</span><span  >,</span> selector<span  >:</span> #<span  >selector</span><span  >(</span>createEnemy<span  >)</span><span  >,</span> userInfo<span  >:</span> <span  >nil</span><span  >,</span> repeats<span  >:</span> <span  >true</span><span  >)</span></code>

Swift 3 makes all labels required unless you specify otherwise,which means the method @R_404_6889@s no longer detail their parameters. In practice,this often means the last part of the method @R_404_6889@ gets moved to be the @R_404_6889@ of the first parameter.

To show you how that looks,here is that Swift 2.2 code followed by its equivalent in Swift 3:

 

Those are methods youcall,but this has a knock-on effect for many methods thatget calledtoo: when you're connecting to frameworks such as UIKit,they expect to follow the old-style "no first parameter @R_404_6889@" rule even in Swift 3.

Here are some example signatures from Swift 2.2:

 

In Swift 3,they all need an underscore before the first parameter,to signal that the caller (Objective-C code) won't be using a parameter label:

 Omit needless words 

When Swift went open source in December 2015,its shiny new API guIDeliness contained three fateful words: "omit needless words." This introduces another huge raft of breaking changes in Swift 3,because it means that method @R_404_6889@s that contain self-evIDent words Now have those words removed.

Let's look at some simple examples first. First,Swift 2.2:

 

Can you IDentify the needless words? When you're working withUIcolor,of course blue is going to be a color,so sayingbluecolor()is needless. When you append one attributed string to another,do you really need to specify that it's an attributed string you're appending as opposed to an elephant?

Here is that same code in Swift 3:

 

As you can see,this makes method @R_404_6889@s significantly shorter!

This change has particularly affected strings,which had repetition all over the place. The best way to demonstrate this is to show before and after code sIDe-by-sIDe,so in the code below the first line of each pair is Swift 2.2 and the second is Swift 3.0:

 

Warning:cAPItalizedis still a property,butlowercaseStringanduppercaseStringhave been transmogrifIEd into the methodslowercased()anduppercased().

I've chosen the examples so far because the jump to Swift 3 isn't vast,but there are quite a few changes that were significant enough to make my brain hit a speedbump– usually when the resulting method is so short that it wasn't immediately obvIoUs what it was.

For example,look at this code:

 

When I first saw that,I blanked: "dismiss what?" That's partly a result of theStockholm syndromethat's inevitable having programmed for@H_419_9@iOS@H_419_9@for so long,but once you learn to reverse the parameter label change and re-add the needless words,you can see it's equivalent to this code in Swift 2.2:

 

A similar change happened toprepareForSegue(),which Now looks like this:

    Intermission  

If you're enjoying this article,you might like my Swift newsletter. I post very rarely,but always include discounts on my books –click here to sign up nowand you'll get aninstant discounton the complete Hacking with Swift e-bookincludinga free update for Swift 3.0.

And Now back to your regularly scheduled broadcast…

UpperCamelCase has been replaced with lowerCamelCase for enums and propertIEs

Although syntactically irrelevant,the cAPItal letters we use to @R_404_6889@ classes and structs,propertIEs,enums,and more have always followed a convention fairly closely: classes,structs,and enums use UpperCamelCase (MyStruct,WeatherType.Cloudy),propertIEs and parameter @R_404_6889@s use lowerCamelCase (emailAddress,requestString).

I say "fairly closely" because there are some exceptions that are going tostopbeing exceptions in Swift 3: propertIEs and parameters that started with initials in Swift 2.2 will Now used lowerCamelCase in Swift 3.

Sometimes this isn't too strange: Swift 2.2 createdNSURLRequestobjects usingNSURLRequest(URL: someURL)–note the cAPItal "URL". Swift 3 rewrites that toNSURLRequest(url: someURL),and also means you'll use things likewebVIEw.request?.url?.absoluteStringfor reading the URL of a web vIEw.

Where it's a bit more jarring is when only part of the property @R_404_6889@ is in caps,e.g.CGcolororCIcolor. Yes,you've guessed it: they becomecgcolorandcicolorin Swift 3,so you'll be writing code like this:

 

This change does help drive consistency: all propertIEs and parameters should start with a lowercase letter,no exceptions.

At the same time enum cases are also changing,moving from UpperCamelCase to lowerCamelCase. This makes sense: an enum is a data type (like a struct),but enum values are closer to propertIEs. However,it does mean that wherever you've used an Apple enum,it will Now be lowercase. So:

 

You get the IDea. However,this tiny change brings something much bigger because Swift's optionals are actually just an enum under the hood,like this:

 

This means if you use.someto work with optionals,you'll need to switch to.someinstead. Of course,you Could always take this opportunity to ditch.someentirely – these two pIEces of code are IDentical:

 Swifty importing of C functions 

Swift 3 introduces attributes for C functions that allow library authors to specify new and beautiful ways their code should be imported into Swift. For example,all those functions that start with "CGContext" Now get mapped to propertIEs methods on a CGContext object,which makes for much more idiomatic Swift. Yes,this means the hIDeous wart that isCGContextSetFillcolorWithcolor()has finally been excised.

To demonstrate this,here's an example in Swift 2.2:

 

In Swift 3 theCGContextcan be treated as an object that you can call methods on rather than repeatingCGContextagain and again. So,we can rewrite that code like this:

 

Note: in both Swift 2.2 and Swift 3.0UIGraphicsGetCurrentContext()returns an optionalCGContext,but because Swift 3 uses method calls we need to safely unwrap before it's used.

This mapPing of C functions exists elsewhere,for example you can Now read thenumberOfPagesproperty of aCGpdfdocument,andCGAffinetransformhas been souped up quite dramatically. Here are some examples showing old and new:

 Verbs and nouns 

This is the part where some people will start to drift off in confusion,which is a shame because it's important.

Here's are some quotes from the Swift API guIDelines:


"When the operation is naturally described by a verb,use the verb’s imperative for the mutating method and apply the “ed” or “ing” suffix to @R_404_6889@ its nonmutating counterpart" "Prefer to @R_404_6889@ the nonmutating variant using the verb’s past participle" "When adding “ed” is not grammatical because the verb has a direct object,@R_404_6889@ the nonmutating variant using the verb’s present participle" "When the operation is naturally described by a noun,use the noun for the nonmutating method and apply the “form” prefix to @R_404_6889@ its mutating counterpart"

Got that? It's no surprise that Swift's rules are expressed using lingustic terminology –it is after all a language! – but this at least gives me a chance to feel smug that I dID a second degree in English. What it means is that many methods are changing @R_404_6889@s in subtle and sometimes confusing ways.

Let's start with a couple of simple examples:

 

Each time Swift 3 modifIEs the method by adding a "d" to the end: this is a value that's being returned.

These rules are mostly innocent enough,but it causes confusion when it comes to array sorting. Swift 2.2 usedsort()to return a sorted array,244)">sortInPlace()to sort an array in place. In Swift 3.0,sort()is re@R_404_6889@d tosorted()(following the examples above),244)">sortInPlace()is re@R_404_6889@d tosort().

TL;DR: This means you need to be careful because in Swift 2.2sort()returned a sorted array,but in Swift 3.0sort()sorts the array in place.

Why all this change?

It's easy to read these changes,some of which are tiny but introduce massive breakage,and imagine that Apple's Swift engineers are just out to make our lives harder. However,the truth is that they are working hard to make sure Swift is as easy to learn,easy to use,and fast as possible,which are three very different prioritIEs.

In particular,I have been struck by how committed the Apple team are to ensuring their changes are discussed and agreed in the open,as part of the Swift Evolution community effort. Every change above went through extensive community discussion before being agreed for Swift 3.0,which is an incredible thing to behold.

You can get involved and help shape these changesgoing forward: they are keen to hear IDeas from a wIDe range of users,and it means the future of Swift really is in your hands.

总结

以上是内存溢出为你收集整理的Swift 3.0一些Api变动全部内容,希望文章能够帮你解决Swift 3.0一些Api变动所遇到的程序开发问题。

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

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

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

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

发表评论

登录后才能评论

评论列表(0条)

保存