1. Swift version detection at compile time
#if swift(>=3.0) print("Running Swift 3.0 or later")#else print("Running Swift 2.2 or earlier")#endif
It differs from the expression described in Swift2 #available
, #available表达式是运行时检查, #if swift(>=3.0)... #else... #endif
is a compile-time check.
A warning: This feature is not available this time because the Swift2.1 compiler does not know #if swift(>=2.2)
what it means. However, as soon as Swift3.0 and all future versions are available, the swift compile-time version check will be a very useful tool.
2. Compile-time selector check
In Swift2.1, the following code is completely fine:
override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem.Add"addNewFireflyRefernce")}func addNewFireflyReference() { gratuitousReferences.append("We should start dealing in black-market beagles.")}
The above code crashes in the application because the navigation bar button calls a method with addNewFireflyRefernce
Refrence
One less letter "E" in the method name. Such simple spelling mistakes can easily cause bugs, so the use of strings as selectors is deprecated in Swift2.2. Use the new syntax: #selector
to replace it.
Using #selector
will check your code at compile time and make sure that the method you want to invoke is real. Even better, if the method does not exist, you will get a compilation error.
Here's how #selector
to rewrite the previous code:
override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = .Add#selector(addNewFireflyReference))}func addNewFireflyReference() { gratuitousReferences.append("Curse your sudden but inevitable betrayal!")}
Here's what to note:
Objective-c selectors (OC selector)
An OC selector is a type that refers specifically to the OC method name. In Swift, the OC selector is represented by the selector structure. You can use the #selector expression to construct a selector. For example let mySelector = #selector(MyViewController.tappedButton)
, use a direct reference to an OC method as a sub-expression. An OC method reference can be enclosed in parentheses, and it can use the "as" operator to eliminate ambiguity between it and the overload. For example let anotherSelector = #selector(((UIView.insertSubview(_:at:)) as(UIView) ->(UIView, Int) ->Void))
.
The sample code is as follows: Adding an event to a button
Import Uikitclass Myviewcontroller:Uiviewcontroller{Let MyButton =UIButton(Frame:CGRect(x:0Y:0, Width: -, Height: -)) Override Init? (Nibname nibnameornil:string?, bundle Nibbundleornil:NSBundle?) {Super. Init(Nibname:nibnameornil, bundle:nibbundleornil) Let action =#selector (Myviewcontroller.tappedbutton)MyButton. AddTarget( Self, Action:action, forControlEvents:. Touchupinside)} func Tappedbutton (sender:UIButton!) {Print ("tapped button")} required init? (Coder:nscoder) {Super. Init(Coder:coder)}}
Official Document Entry
3, more keywords as the parameter label
There are many keywords in swift, like class
,, fund
let
and these have public
their special meanings, so they cannot be used as identifiers. In Swift, you are allowed to use keywords as parameter tags. If you put them in quotation marks just like the following code:
func visitCity(name: String, `instate: String) { print("I‘m going to visit \(name) in \(state)")}visitCity("Nashville", `in"Tennessee")
inout
var
let
Any keyword can be used as a parameter label in addition to, and Swift2.2. If you enclose the keyword in quotation marks in your code, you will get an fix-it warning from Xcode, which will automatically remove the quotation marks if you click the warning. The code that removes the quotation marks is likely to be this:
StringinString) { print("I‘m going to visit \(name) in \(state)")}visitCity("Nashville"in"Tennessee")
4, built-in meta-group comparison
Swift2.2 describes the ability to compare two tuples for equality. This means that it checks whether each element in the tuple matches the elements in another tuple, and returns true if all elements match.
For example, the following code will print a "mismatch":
let singer = (first"Taylor"last"Swift")let alien = (first"Justin"last"Bieber")if singer == alien { print("They match! That explains why you never see them together…"else { print("No match.")}
The Swift2.2 tuple cannot have more than 6 comparison elements.
Warning: Swift2.2 will ignore your element name when checking for equality, so "singer" and "Bird" in the code below will be considered equal:
let singer = (first"Taylor"last"Swift")let bird = (name"Taylor"breed"Swift")if singer == bird { print("This explains why she sings so well."else { print("No match.")}
5. Splat syntax for tuples is deprecated
Before Swift2.1, it is possible to use a tuple to populate the parameters of a function. So, if you have a function with two parameters, you can call it with a tuple of two elements, as long as the tuple has the correct type and element name, for example:
StringInt) { print("\(name) is \(age) years old")}let person = ("Malcolm Reynolds"49)describePerson(person)
This syntax is called "Tuple splat Syntax". This is not in line with Swift's own description of the language habits and readability of the style. Therefore, it is deprecated in Swift2.2.
6. C language-style for loop is deprecated
Even though Swift has many types of looping syntax to choose from, the C-style for loop is still part of the language and is occasionally used. For example:
fori0i10i{ print(i)}
This syntax has been deprecated in Swift2.2 and may be removed in Swift3.0.
If you are using Xcode, you may get a fix-it warning that will convert your C-style for loop into modern Swift. Now we should write this:
forin010 { print(i) }
However, the repair function is limited, so there are some things you need to do yourself. For example, the following two loops will not fix it for you:
fori10i0i{ print(i)}fori0i10i2{ print(i)}
In the first case, you should use the "(1 ... (). Reverse () "creates a reverse range. This cannot be written as "I in 10 ... 1 ", so there is no problem writing the compilation, but it crashes at run time. In the second case, you should use "Stride (To:by:)" to accumulate 2. Therefore, the correct way to rewrite the above two loops is as follows:
forin (1...10).reverse{ print(i)}forin0.stride(to10by2{ print(i)}
7, + + and--operators are deprecated
If you've used a C-style for loop, it's certainly not unfamiliar with the + + and--operators. In Swift3.0, the + + and – operators are also deprecated. such as:,,,, i++
i--
++i
--i
i = i++
These are not used. Instead: i += 1
or i -= 1
, like the code in the example above, Xcode will also provide fix-it repair warnings to help you fix your code.
8. The var parameter is deprecated
Before Swift2.2, if you want to modify function parameters inside a function, you can declare the function arguments as VAR, for example:
name: String) { namename.uppercaseString print("Hello, \(name)!"name"Taylor"greet(name)print("After function, name is \(name)")
It's so confusing that the final print () statement output is "Taylor" or "Taylor"? There is more confusion in the InOut keyword: The following example uses InOut instead of using Var, and then adds a "&" symbol. This code is generated:
name: String) { namename.uppercaseString print("Hello, \(name)!"name"Taylor"greet(&name)print("After function, name is \(name)")
When the program runs, the Var example and the inout example produce different output results, because changing the Var parameter only applies to the inside of the function, and changing the InOut parameter directly affects the initial value.
So, in Swift2.2, this confusion is clear by discarding the Var keyword in the function arguments. will be removed from the Swift3.0. How do you also want to follow the previous habit of writing, can be like this:
String) { let uppercaseName = name.uppercaseString print("Hello, \(uppercaseName)!") }
9. Rename the debug identifier
The Swift compiler automatically provides some useful symbols when debugging, and __FILE__
is replaced with the current Swift file name, representing the __LINE__
number of rows, and so on. In Swift2.2, these old identifiers are deprecated, used #file
,, #line
#column
, and #function
superseded.
The differences between the old and new syntax are listed in the following example:
in state: String) { // old - deprecated! print("This is on line \(__LINE__) of \(__FUNCTION__)") print("I‘m going to visit \(name) in \(state)") // new - shiny! print("This is on line \(#line) of \(#function)") }
As with other changes, Xcode will have a fix-it warning to help you update the correct code.
This article is from the network, the following will be continuously updated and perfected. The above part is my own study and understanding, welcome to learn to communicate together! A lot of criticism and correction!
The resources are as follows:
(1) New Features in Swift 2.2
if you want to reprint, please specify the source: Swift2.2 new Features
Swift2.2 new Features