Go New features for Swift 3

Source: Internet
Author: User
Tags gcd naming convention



Wen/mango_to (author of Jane's book)
Original link: http://www.jianshu.com/p/dc80e290806f


Objective


Swift 3 will meet with you later this year, which will bring huge changes to the code level for swift developers.
If you haven't recently followed the pace of swift evolution, you may ask what the changes are, how it will affect your code, and when you should move to Swift 3. Then this article will answer for you.
In this article, I will highlight the most important changes in Swift 3, as these will affect your code. Let's dig deep together!


Begin


The Swift 3 Preview version is now available in the Xcode 8 beta. Although the evolution of Swift 3 is nearing its end, some changes will be made in the next few months. The features of Swift 3 were finalized in 2016, when the release of Xcode 8 was released, so you had to postpone the release date of the app written by Swift 3.



To enable developers to migrate to Swift 3 in their own way, as a small upgrade package, Xcode 8 will contain swift 2.3. From a developer's point of view, the Swift 2.3 is the same as Swift 2.2, but it will support more new SDKs and the new Xcode features announced on WWDC. Once Xcode 8 is released and you haven't migrated to Swift 3, you can submit an app written in Swift 2.3.



I suggest you test the features we discuss in the playground, and you might be able to run the migration Assistant in one of your projects (or don't take the company project as a mouse) to feel the changes that come with the new technology. Because until the full version of Xcode 8 is released, Swift 3 is finalized so that you can publish the app, so you should consider waiting until everything has been finalized and moved to Swift 3.


Migrating to Swift 3


When switching to Swift 3, you will find that almost all files need to be changed! This is mainly because the Cocoa API naming has changed. Or more precisely, the API is the same, but now the naming of Oc,swift is not uniform. Swift wants to make Swift's writing more natural in the coming time.



Apple integrates the migration Assistant in Xcode 8, which intelligently helps you to fix these changes. But don't be surprised, if you want to modify the place yourself, the migration Assistant will not automatically help you with it.



You can quickly switch to Swift 2.3 or Swift 3. If you want to convert back, you can do this in Xcode: Edit > Convert > to Current Swift Syntax .... The compiler is as smart as the migration assistant, and if you use the old API on a method call, the compiler provides an optional option to help you fix it so you can use the correct modern API.



The most important message is that theSwift 3 goal is the last version to make a major change . So when Swift iterates from one version to another, you can keep your code intact. Although the SWIFT core team cannot predict the future, they promise to provide a fairly long cycle of obsolescence if they really need to compromise source compatibility. That means the swift language has source stability, which will encourage more conservative companies to adopt the swift language.



It is said that the goal of binary stability has not been achieved. At the end of the article, you will learn more about the effects of binary stability.


Already implemented---Swift evolution proposal


Since Swift Open source, community members have made hundreds of proposals for Swift's change. Most of the proposals (currently 70, or more) were accepted after the discussion. The rejected proposals are also decisions that have been made after intense discussion. Eventually, however, the Swift core team will make decisions on all proposals.



Swift's core team is engaged in a wide range of interactions with the community. In fact, Swift has gained more than 30,000 stars on GitHub. Day after day, several proposals have been put forward every week. Even if Apple engineers want to make a change, they will open a new warehouse on GitHub and offer a proposal.



In the following section, you will see a label such as [SE-0001]. These are the swift Evolution offer numbers. The numbered proposals here are accepted and will be implemented in Swift 3. Each proposed link is also provided, and you can see the specifics of each change.


API changes


The biggest update to the Swift 3 is that the standard library uses a unified naming convention. The API Design Guide includes the team's code to build Swift 3 compliance, which is valuable for writing readability and maintainable code. The core team practices this guideline: Good API design always takes into account the invocation scenario . They strive to make the use of APIs clearer. Needless to say, the next is the most likely to affect your change.


First parameter label


We start with an instance that we use every day.




The first parameter in the function and method will require a note unless you have other requirements. Previously, when you called a function or method, you omitted the first parameter tag [SE-0046]:


//The first one is the old way in Swift 2, the next one is the new way in Swift 3.
"RW".writeToFile("filename", atomically: true, encoding: NSUTF8StringEncoding)

"RW".write(ToFile:"filename", atomically: true, encoding: String.Encoding.uft8)

SKAction.rotateByAngle(CGFloat(M_PI_2), duration: 10)
SKAction.rotate(byAngle: .pi / 2, duration: 10)

UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
UIFont.preferredFont(forTextStyle: UIFontTextStyleSubheadline)

Override func numberOfSectionsInTableView(tableView: UITableView) -> Int
Override func numberOfSections(in tableView: UITableView) -> Int

Func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView?
Func viewForZooming(in scrollView: UIScrollView) -> UIView?


NSTimer.scheduledTimerWithTimeInterval(0.35, target: self, selector: #selector(reset), userInfo: nil, repeats: true)
Timer.scheduledTimer(timeInterval: 0.35, target: self, selector: #selector(reset), userInfo: nil, repeats: true) 


Note how the method definition is used for external names such as: "of", "to", "with", and "in" prepositions.
If the method call does not have a preposition and does not require a label, you can explicitly replace the first parameter name with an underscore.


 
 
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { ... }
override func didMoveToView(_ view: SKView) { ... }


In many programming languages, the method will have a base name and provide a different parameter name. Swift is no exception, and now you will often run into overloaded methods because the API is more straightforward. Here is an example that shows two forms of the Index () method:


 
 
let names = ["Anna", "Barbara"]
if let annaIndex = names.index(of: "Anna") {
    print("Barbara‘s position: \(names.index(after: annaIndex))")
}


In short, the change in parameter names makes the method names more uniform and easier to learn.


Omit unnecessary words


In the previous version iterations of the Apple Library, the method includes a name that indicates the return value. This is not necessary due to the type checking of the Swift compiler. After careful examination, the team filtered out the noise leaving only a signal, and many of the repeated words were removed.




The API is more intelligent in converting OC libraries to native Swift [SE-0005]:


 
//The first one is the old way in Swift 2, the next one is the new way in Swift 3.
Let blue = UIColor.blueColor()
Let blue = UIColor.blue

Let min = numbers.minElement()
Let min = numbers.min()

attributedString.appendAttributedString(anotherString)
attributedString.append(anotherString)

Names.insert("Jane", atIndex: 0)
Names.insert("Jane", at: 0)

UIDevice.currentDevice()
UIDevice.current 
Modern GCD and Core Graphics


Speaking of objections to the old API, GCD and core graphics became the two most needed to be transformed.




GCD is used in multi-threaded tasks, such as time-consuming computational work or communication with the server. You can avoid blocking user threads by switching tasks to different threads. The Libdispatch Library is written in C and uses the C language style API. These APIs are now redesigned in the native swift style.


// Swift 2 old way
Let queue = dispatch_queue_create("com.test.myqueue", nil)
Dispatch_async(queue) {
     Print("Hello World")
}

// Swift 3 new way
Let queue = DispatchQueue(label: "com.test.myqueue")
Queue.async {
     Print("Hello World")
} 


Similarly, the Core Graphics are written in C, which used a very dejected function call. Take a look at the new method [SE-0044]:


// Swift 2 old method
Let ctx = UIGraphicsGetCurrentContext()
Let rectangle = CGRect(x: 0, y: 0, width: 512, height: 512)
CGContextSetFillColorWithColor(ctx, UIColor.blueColor().CGColor)
CGContextSetStrokeColorWithColor(ctx, UIColor.whiteColor().CGColor)
CGContextSetLineWidth(ctx, 10)
CGContextAddRect(ctx, rectangle)
CGContextDrawPath(ctx, .FillStroke)
UIGraphicsEndImageContext()

// Swift 3 new method
Guard let ctx = UIGraphicsGetCurrentContext() else {
     Return
}
Let rectangle = CGRect(x: 0, y: 0, width: 512, height: 512)
ctx.setFillColor(UIColor.blue.cgColor)
ctx.setStrokeColor(UIColor.white.cgColor)
ctx.setLineWidth(10)
ctx.addRect(rectangle)
ctx.drawPath(using: .fillStroke)

UIGraphicsEndImageContext() 
Enumerate Cases First Letters


Another alternative to the SWIFT encoding that you are accustomed to is that the enumeration case now uses Lowercamelcase. This will make them more consistent with other attributes-[SE-0006]:


//The first one is the old way in Swift 2, the next one is the new way in Swift 3.
UIInterfaceOrientationMask.Landscape
UIInterfaceOrientationMask.landscape

NSTextAlignment.Right
NSTextAlignment.right

SKBlendMode.Multiply
SKBlendMode.multiply 


Uppercamelcase now has a reservation only on the type name and protocol name. This may take some time to adapt, but the swift team has a reason to do so---they are trying to reach a consensus.


Functions that have return values and that modify themselves


The Swift standard library is becoming more and more unified in the noun, verb function naming. You name a function based on the effect of the action. The rule of thumb is that if it contains a suffix like "-ed" or "-ing", it is considered a noun function. The noun function returns a value. If it does not have a suffix, then it is likely to be a necessary verb. These "verb" functions perform actions in reference memory. This is also known as modifyingin place. The following are the function pairs that obey the noun/verb rules. Here are some function pairs [SE-0006]:


customArray.enumerate()
customArray.enumerated()

customArray.reverse()
customArray.reversed()

customArray.sort() // changed from .sortInPlace()
customArray.sorted()


Here are some behavioral differences:


Var ages = [21, 10, 2] // variable, can be modified
Ages.sort() //modify in place, the value is now [2, 10, 21]

For (index, age) in ages.enumerated() { //"-ed" noun Returns a copy.
     Print("\(index), \(age)") //1,2 \n 2,10 \n 3,21
} 
function type


function declarations and function calls always require parentheses to include parameters:


Func g(a: Int -> Int) -> Int->Int { ... }//swift 2 old method


However, when you use a function type as a parameter, you might write:


Func g(a: Int -> Int) -> Int->Int { ... }//swift 2 old method


You may notice that this is very difficult to read. Where does the parameter end? Where does the return value begin? The correct definition of this function in Swift 3 is [SE-0066]:


Func g(a:(Int) -> Int) -> (Int) -> Int { ... }//swift 3 New method


Now the argument list is surrounded by parentheses, followed by the return type. The function becomes clearer, and as a result, the function type becomes easier to identify.
Here are some robust comparisons:


//swift 2 old method
Int -> Float
String -> Int
T -> U
Int -> Float -> String

//Swift 3 new method
(Int) -> Float
(String) -> Int
(T) -> U

(Int) -> (Float) -> String 
New API


Although the Swift 3 biggest update is a modification to the existing API, the SWIFT community has done a lot of work to add new APIs.


Gets the containing type (or implied type).


When you define a static property or method, you always call them directly by type:


CustomStruct.StaticMethod()


If you write code in a type, you also need a type name to invoke the static method. For clarity, you can now call self to get the implied type. The capital letter "S" obtains the Self's type, and the lowercase letter "s" gets the instance of self.




Here will explain how it works [SE-0068]:


Struct CustomStruct {
     Static func staticMethod() {}

     Func instanceMethod() {
         Self.staticMethod () / / inside the type body, before you write CustomStruct.staticMethod ()
     }
}

Let customStruct = CustomStruct()
customStruct.Self.staticMethod() 

Note: This feature will be added to Swift 3, but it is not yet available in Xcode 8 Beta 5.

Inline sequence


Sequence (first:next:) and Sequence (State:next:) are global functions that return an infinite sequence. You can give them an initial value, or initial state, and they will be applied to a closure in a lazy load [SE-0094]:


 
 
for view in sequence(first: someView, next: {$0.superView}) {
       //someView, someView.superView, someView.superView.superView, ...
}


You can limit the sequence by adding a prefix operator


 
for x in sequece(first: 0.1, next: {$0 * 2}).prefix(while:{$0 < 4}) {
       //0.1, 0.2,0.4,0.8,1.6,3.2
}

Note: This feature will be added to Swift 3, but it is not yet available in Xcode 8 Beta 5.

Other piecemeal changes
    • #keyPath () works like #selector () , which avoids typos in the use of string-type APIs.

    • You can now invoke the PI through the type you want to use, for example: Float.pi, Cgfloat.pi. Most of the time, the compiler can infer the type: let Circumreference = 2 *. Pi * radius[se-0067]

    • The prefix ns for the old function type is removed. You can now use calendar, Date instead of Nscalendar and NSDate.
Promotion on the tool


Swift is a language that uses the development environment to write swift code-the Apple developer is Xcode! The changes to the tool will affect how you write your code every day.
Swift 3 fixes the bugs in the compiler and integrated development environment. It also improves the accuracy of error and warning messages. As you can see, Swift runs and compiles faster every time a new version is released.


    • By improving the string hash, the string type dictionary is 3 times times faster.
    • Transfers object storage from the heap to the stack, up to 24 times times faster (in some cases)

    • The compiler now caches multiple files at once (optimized throughout the module)

    • Code volume optimization reduces the volume after the SWIFT code is compiled. The size of the demo-demobots compiled by Apple is reduced to 77% of the original.


Xcode is learning to think in the form of native Swift:


    • When you right-click the API method like sort (), you will jump to the definition of the method, and you will usually be taken to the strange header file. In Xcode 8, as you expected it is an extension method of the array.


Swift snapshots are like subsequent versions of Swift evolution. Before fully integrating into Xcode, they provide an opportunity to use the new syntax. Xcode 8 can load and run a swift snapshot in playground.


Swift Package Manager


The swift source is actually a collection of several warehouses, including: language, core library, and package Manager. Together, this suite forms the swift we know. The SWIFT Package Manager defines a simple directory structure for your shared code and engineering code.
Similar to the Cocoapods or Carthage that you are familiar with, Swift package Manager downloads dependencies and compiles and links them to create libraries and executables. Swift 3 is the first version that supports Swift Package manager. Currently, more than 1000 libraries already support the Package Manager, and more libraries will be added in the next few months.


Expected future features


As mentioned before, Swift 3 allows you to keep your code in the swift version iterations by avoiding significant changes. But in fact, some lofty goals have not been achieved, namely generics additions and Abi stabilization.
Generic additions include recursive protocol constraints and having a constrained extension adhere to a new protocol (for example: an array of elements that comply with Equatable also complies with the Equatable protocol. Swift cannot announce ABI stability until these features are complete.



ABI stabilization allows different versions of Swift applications, libraries to compile, link, and communicate with each other. Abi stabilization is critical for third-party libraries that do not provide source code, because the new version of Swift requires that they not only update their codes, but also rebuild the framework.
In addition, the ABI stabilization eliminates the need to assemble swift standard libraries and binaries for the iOS and MacOS applications currently created by Xcode. Binary files are now bundled with 2M of extra-sized files, which ensures that they can run on future operating systems.



So all in all, you can keep your source code in the swift version iterations, but the compatibility issues between versions and compiled binaries are not resolved.


Summarize


As the community continues to practice, Swift continues to evolve. Although it is still in its infancy, the language has a lot of momentum and a bright future. Swift is already running on Linux, and in the next few years you will most likely see it running on the server side. Designing a language from scratch has its advantages, and once the ABI stabilizes, the likelihood of breaking it is very small. It is a good chance to correct the language and never regret it. (Ha, how the Swift 3 is the Great Expectations!?? )



Swift is expanding. Apple is also using their own products. The Apple team uses Swift in the Music app, console, Sierra Pip, Xcode document viewer and the ipad version of Swift Playgroud.
Here, there should be a big impetus for non-procedural people to learn swift through ipad or education programs.
The key here is that Swift is still rising: the better the name becomes, the clearer the code becomes, and the tools to help you migrate. If you are inspired and want to dig deeper, you can watch WWDC session videos.



Go New features for Swift 3


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.