What's new in Swift 3

Source: Internet
Author: User
Tags gcd naming convention unpack

Original: What's New in Swift 3
COSMIN PUP? Z?
Translator: Kmyhy

At the WWDC, Apple integrated the Swift 3 in Xcode 8 Beta, and the final version needed to be released at the end of the year. This is the first version of the Swift source, which will support Mac OS X and Linux at the same time. If you're concerned about the Swift Evolution, which started last November, it has even been able to run on the IBM sandbox, and this language has really turned upside down. If you use Xcode 8 to edit your case, you'll find that you can't edit it at all.

The change in Swift 3 is mainly focused on two areas:

    • Remove the "abandoned" feature that is stated in Swift 2.2
    • Make the language more "first"

Let's start with a simple beginning, the language feature that was removed in Swift 3. These features are some of the caveats you've seen in Xcode 7.3.

+ + and – operator

Self-increment and self-subtraction are inherited from C language, and their function is simple: to subtract or add 1 on the basis of a variation.

var i = 0i++++ii----I

However, it is often overwhelming to choose which of these operators to use. Both the self-increment and the self-subtraction operators have two ways of using it: the front or the back-they are completely hidden in the bottom layer, and the return value may or may not be useful to you, but fortunately we also have operator reload.

For starters, they're too hard to control, so now they're being removed--now they're completely replaced by + = and ﹣=:

var i = 0i + = 1i-= 1

Although the value of the resurrection is shorter, you can use + and ﹣ to achieve the same purpose as long as you wish:

i = i + 1i = i-1

[Ecko_alert color= "Gray"] language: If you want to know the original proposal for this change, you can read Chris Lattner's advice on removing ++/– operators. [/ecko_alert]

The For loop of C language style is a historical

The most common use of self-increment and self-subtraction is the canonical cycle of C language. When the self-increment, the self-subtraction operator is removed, it also means that the historical mission of the C code cycle is finally ended, because the use of the for-in loop can be done in the same way as the classic loop does.

If you have a certain programmed experience, then print numbers from 1 to 10 and you can use the For loop to actually:

for (i1i10i{  print(i)}

In Swift 3, it is no longer permissible to do so. The following is the same function of the Swift 3-note that the closure operator ... Use of:

For I in 1...10 {  print (i)}

In addition, you can also use the For Each loop and the closed package, shortcut parameters to the same purpose-more on the cycle of discussion, please refer here.

(1...10). ForEach {  print ($)}

[Ecko_alert color= "Gray"] language: If you would like to know the original suggestion for this change, please read the Erica Sadun for the reference to the C language style. [/ecko_alert]

var is removed from the function parameters

Function parameters are generally used when you do constants, because in a method you do not normally modify their values. But in some cases, you need to voice them as variables. In Swift 2, you can use Var to trim a function. Once the parameters are modified by Var, it creates a local variable, so you can modify its value in the function.

For example, the following function will judge the maximum number of two numbers-if you forget your high school math, please look here first:

Func gcd (Var a:int, var b:int), Int {  if (a = = b) {    return a  }  repeat {    if (a > B) {      a = A    -B} else {      b. = B-a    }  } while (A! = b)  return a}

The algorithm is simple: If two numbers are equal, return one of them. Otherwise, compare the two, subtract the smaller one with the big one and give the result to the larger one until they are exactly equal and eventually return to one of them. As you can see, both A and B are decorated with Var, so in the function we could change the values arbitrarily.

The Swift 3 is no longer allowed to do so, because it allows the developers to confuse Var with inout. Therefore, the new version directly forbid the use of Var in the function parameters.

Therefore, the GCD function needs to be used in other ways in Swift 3. You need to save the values in a local variable:

Func gcd (A:int, b:int), Int {  if (a = = b) {    return a  }  var c = a  var d = b  repeat {    if (C > D) {      c = c-d    } else {      d = d-c    }  } while (c! = d)  return C}

If you would like to know the original suggestions for this change, please read the initial suggestions.

The number of references to a function is a colleague

A list of the parameters of a function, which is actually represented by a tuple (tuple), so you can adjust the function in the form of a tuple, as if you were using a tuple with the same function as the prototype. Take the GCD () function as an example, you can adjust it like this:

GCD (8, B:12)

You can also adjust it like this:

Let number = (8, b:12) gcd (number)

As you can see, the Label of the first reference in Swift 2 (also called the external name) is not required. However, the name of the second reference (and the remainder of the remaining parameters) is required.

This language is also confusing for novices, so the use of this reference is a rule. In Swift 3, you must adjust this function:

GCD (A:8, B:12)

It is necessary to explicitly specify the first name. Otherwise, Xcode 8 will prompt you for bugs.

Your first reaction to this may be "God!" It's going to take a lot of changes to my code! ”。 You're right, that's a really good amount of change. Therefore, Apple provides a way to ignore the first name when a function is used. You can add a lower line before the first one:

Func gcd (_ A:int, B:int), Int {...}

In this way, you don't have to modify the original function-that is, you don't need to write the first name. This will simply reduce the amount of code from Swift 2 to Swift 3.

[Ecko_alert color= "Gray"] language: to understand the original suggestion of this change, please read this suggestion. [/ecko_alert]

Cannot represent Selector with string

Let's create a button that allows it to perform certain actions when touched--the assumption can only be made with playground and not with Interface Builder, and this code should be programmed as:

1import uikitimport xcplayground//2class responder:nsobject {  func tap () {    print ("button pressed")  }} Let responder = responder ()//3let button = UIButton (type:. System) button.settitle ("button", Forstate:. Normal) Button.addtarget (Responder, Action: "Tap", forControlEvents:. Touchupinside) Button.sizetofit () Button.center = Cgpoint (x:50, y:25)//4let frame = CGRect (x:0, y:0, width:100, height :) Let view = UIView (frame:frame) View.addsubview (button) XCPlaygroundPage.currentPage.liveView = view

The code is a bit more, so let's break it down into several steps to say:

    1. Into the UIKit and xcplayground framework-so that we can create a button and display it in Playground's helper editor.

      Note : You can open the Assistant editor and interact with the button via the Show Assistant Editor menu, Assistant Editor, View.

    2. Defining a tap method, this method will be touched at the touch button, and a responder to the icon to the button Target──responder must be inherited from NSObject, because the selector is only valid for the Objective-c method.

    3. Create a button and set its nature.

    4. Create a view, specify its frame when it is initialized, then add the button to it and then display it on the Playground assistant editor.

Note the code that is prominently displayed. The selector of the button is specified with a string. If you write this wrong, the code will still be able to be translated, but when it does, it collapses bulb because it cannot find a corresponding method.

To solve this potential problem in editing, Swift 3 uses the #selector() keyword to denote selector. This way, if you write the wrong method name, the translator will check the problem in advance.

Button.addtarget (Responder, Action: #selector (Responder.tap), for:. Touchupinside)

[Ecko_alert color= "Gray"] language: to understand the original suggestion for this change, please read Doug Gregor's advice. [/ecko_alert]

This is the language feature that has been removed in Swift. Now let's look at some of the changes that have made Swift more "advance".

Key-paths no longer use strings

This feature is somewhat similar to the previous one, but it is used for KVC (key value codes) and KVO (key value observation).

Class Person:nsobject {  var name:string = ""  init (name:string) {    self.name = name  }}let me = person (nam E: "Cosmin") Me.valueforkeypath ("name")

You created a person class, which is a key-value code-compatible, passed my name in the specified initialization method, and then went through Key-path to read my name. Similarly, if you make Key-path wrong, the app will collapse bulb, I'll be very angry! :(

Fortunately, Swift 3 solves this problem. The Key-path string now needs to be replaced by a #keyPath() table:

Class Person:nsobject {  var name:string = ""  init (name:string) {    self.name = name  }}let me = person (nam E: "Cosmin") Me.Value (Forkeypath: #keyPath (person.name))

[Ecko_alert color= "Gray"] Editor's note: for this original suggestion, you can check out David Hart's advice. [/ecko_alert]

The Foundation type name no longer requires NS front able

NS before able is finally removed from the Foundation type name-if you want to know the original suggestion for this change, please look here. Typical examples are JSON parsing:

Let file = Nsbundle.mainbundle (). Pathforresource ("Tutorials", OfType: "JSON") Let URL = Nsurl (fileurlwithpath:file!) Let data = NSData (contentsofurl:url) Let JSON = try! Nsjsonserialization.jsonobjectwithdata (data!, Options: []) print (JSON)

In the process of reading JSON numbers from a file, we used several Foundation types:
Nsjsonserialization, NSData, NSBundle, Nsurl,

In Swift 3, the NS front able is removed, so the parsing process above becomes:
URL, Data-jsonserialization, Bundle

Let file = Bundle.main (). Pathforresource ("Tutorials", OfType: "JSON") Let URL = URL (fileurlwithpath:file!) Let data = try! Data (contentsof:url) Let JSON = try! Jsonserialization.jsonobject (with:data) print (JSON)

[Ecko_alert color= "Gray"] language: to find out the original suggestion for this change, please check out this suggestion from Tony Parker and Philippe Hausler [/ecko_alert]

M_pi and. PI

Let's calculate the circumference and the circumference of the circle using a circular radius:

Let R =  3.0let circumference = 2 * M_PI * rlet area = M_PI * R * r

In the old Swift version, M_PI represents the circular frequency. In Swift 3, the pi is placed inside the float, Double, and CGFloat types:

Float.piDouble.piCGFloat.pi

So the code for the preceding (calculated circumference and polygon) codes can be programmed with Swift 3:

Let r = 3.0let circumference = 2 * Double.pi * rlet area = Double.pi * R * r

Because of the type of push, we can even ignore the type name, so the code can be simplified as:

Let r = 3.0let circumference = 2 *. pi * Rlet area =. Pi * R * r
GCD

GCD (Grand Central Dispath) is often used to perform network operations without blocking the user interface in the main thread. It is written in C, so its API is difficult for beginners to understand, especially if you want to do some work in the interracial team:

Let queue = Dispatch_queue_create ("Swift 2.2", nil) Dispatch_async (queue) {  print ("Swift 2.2 queue")}

Swift 3 Removes these formulations and the tedious of the language, and instead turns to a vision-oriented approach to the reality:

Let queue = dispatchqueue (Label: "Swift 3") Queue.async {  print ("Swift 3 Queue")}

[Ecko_alert color= "Gray"] language: to understand the original suggestion for this change, please read Matt Wright's suggestion [/ecko_alert]

The Core Graphics becomes more "Swift"

The Core graphics is a powerful graphics framework, but uses the same API as GCD C:

Let frame = CGRect (x:0, y:0, width:100, height:50) class View:uiview {  override func DrawRect (rect:cgrect) {    Let context = Uigraphicsgetcurrentcontext () let    blue = Uicolor.bluecolor (). Cgcolor    cgcontextsetfillcolorwithcolor (context, blue) let    red = Uicolor.redcolor (). Cgcolor    cgcontextsetstrokecolorwithcolor (context, red)    cgcontextsetlinewidth (context, ten)    Cgcontextaddrect (context, frame)    cgcontextdrawpath (context,. Fillstroke)  }}let Aview = View (frame:frame)

You need to specify the frame of the view, inheriting the UIView category, and re-writing the DrawRect method to customize the drawing operation, so that the view is rendered in a different way.

In Swift 3, a completely new approach was used to first acquire the former drawing context using the Core graphic──, unpack it, unpack it into a context image, and then pass through the context to perform all the graphics operations:

Let frame = CGRect (x:0, y:0, width:100, height:50) class View:uiview {  override Func Draw (_ Rect:cgrect) {    gu ARD Let context = Uigraphicsgetcurrentcontext () else {      return    } let    blue = Uicolor.blue (). Cgcolor    Context.setfillcolor (blue) let    red = uicolor.red (). Cgcolor    Context.setstrokecolor (red)    Context.setlinewidth    Context.addrect (frame)    Context.drawpath (using:. Fillstroke)  }}let Aview = View (Frame:frame)

Note : The picture context is empty until the view is adjusted with its DrawRect method, so you need to unpack it with the guard language--read more here.

Verb/noun naming specifications

And then I'll talk a little bit about the language! :) Swift 3 divides the method into two categories: a return value-named with a noun, and a manipulation of the verb-using verbs to name it.

Print the following numbers from 10 to 1:

For I in (1...10). Reverse () {  print (i)}

The reverse () method is used to reverse the sequence. In Swift 3, this method should be used as a noun because it returns the original area in reverse order. So, it adds an Ed able after this method:

For I in (1...10). Reversed () {  print (i)}

One of the most common uses of Yuanxi is to print the contents of a group:

var array = [1, 5, 3, 2, 4]for (index, value) in Array.enumerate () {  print ("\ (index + 1) \ (value)}

In Swift 3, this method should be used as a noun, because it also returns a tuple composed of the indexes and values of the elements of the previous group. So it adds an Ed able after this method:

var array = [1, 5, 3, 2, 4]for (index, value) in array.enumerated () {  print ("\ (index + 1) \ (value)}

Another example is the sequencing of the numbers. Below we will sort a number in ascending order:

var array = [1, 5, 3, 2, 4]let sortedarray = Array.Sort () print (Sortedarray)

In Swift 3, this method should use the noun because it returns a sorted number of numbers. So the sort method is now named sorted method:

var array = [1, 5, 3, 2, 4]let sortedarray = array.sorted () print (Sortedarray)

Let's do the work directly on the numbers and get rid of the middle variables. In Swift 2, you'll use this code:

var array = [1, 5, 3, 2, 4]array.sortinplace () print (array)

You pass the sortInPlace () method to sort a variable. In Swift 3, this method name should be verb because it directly acts on the actual sort operation without returning anything. You just need to use the simplest words to describe the motion. So sortInPlace () should be replaced by sort ():

var array = [1, 5, 3, 2, 4]array.sort () print (array)

[Ecko_alert color= "Gray"] language: Please read the API Design Guide for the initial advice on this naming convention. [/ecko_alert]

API more "Swift"

Swift 3 uses a simple philosophy to rule its api── delete an unused word if it is superfluous or is capable of being pushed out through the context, then delete it:----

    • XCPlaygroundPage.currentPageChange toPlaygroundPage.current
    • button.setTitle(forState)Change tobutton.setTitle(for)
    • button.addTarget(action, forControlEvents)Change tobutton.addTarget(action, for)
    • NSBundle.mainBundle()Change toBundle.main()
    • NSData(contentsOfURL)Change toURL(contentsOf)
    • NSJSONSerialization.JSONObjectWithData()Change toJSONSerialization.jsonObject(with)
    • UIColor.blueColor()Change toUIColor.blue()
    • UIColor.redColor()Change toUIColor.red()
Value of the stamp

Swift 3 regards the value as its own and therefore uses the "small Camels peak method" instead of the "big Camels Peak method" to name it:

    • .SystemChange to.system
    • .TouchUpInsideChange to.touchUpInside
    • .FillStrokeChange to.fillStroke
    • .CGColorChange to.cgColor
@discardableResult

In Swift 3, if you do not use the return value of a method or function, Xcode will display a warning, for example:

In the code above, the Printmessage method returns a string. However, this return value is not useful when we adjust the method, which may lead to potential problems, so the Swift 3 translator will issue a warning.

But in some cases, we actually do not need to retain the return value, so you can use a @discardableResult to indicate that the method does not require this warning:

Override Func Viewdidload () {    super.viewdidload ()    printmessage (message: "Hello Swift 3!")} @discardableResultfunc Printmessage (message:string), String {let    outputmessage = "Output: \ (message)"    Print (outputmessage)    return outputmessage}
End Bundle

Introduction to Swift 3 is here. The release of the new Swift version has made the language more useful. The same time it contains a lot of functionality, it can also have a very big impact on the code you are now in. I hope this tutorial will allow you to better understand these changes and save you the time it costs to upgrade your Swift case.

All of the code in this tutorial can be downloaded here. I've passed the test in Xcode 8 beta. Please ensure that you are running this case in Xcode 8.

If you have any questions or suggestions, please tell me. I wish you coding happiness! :)

Translator's introduction

Yang Wang Yan, male, Chinese mainland people, CSDN Blog expert (personal blog http://blog.csdn.net/kmyhy). Started learning Apple IOS in 2009, proficient in the O-c/swift and Cocoa Touch framework, and developed multiple store applications and business apps. Passionate about writing, having and translating a number of technical expertise, including: "Enterprise-class IOS to Combat", "IPhone & IPad Business Mobility Tips", "IOS8 Swift Guide", "read to Busy People Swift" (co-translation), "ios Swift" Game development Cookbook "and so on.

What's new in 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.