iOS Development Series--swift 3.0

Source: Internet
Author: User
Tags constant definition

Overview

From the time of writing the first Swift article to now Swift has grown from 1.2 to today's 3.0, during which the part of the code in the first article has not been able to run in the current Xcode environment because Swift is not backwards compatible in the development phase. Apple unveiled Swift3.0 on WWDC16, which shows Apple's focus on swift and the progress of Swift's open source for half a year. While Swift3.0 changes will make your program almost always error-free for developers, imagine if Apple didn't pursue the ultimate spirit and how to make so many changes. Today's article will focus on: What's new in Swift 3.0? From the Swift compiler and standard library two aspects to explain the change from Swift3.0.

compiler and syntax change function or method parameters
    • The parameter name must be specified at the beginning of the first argument when calling a function or method

In the history version of Swift, there is no need to specify any function arguments when calling a function (or to specify the parameter name starting from the second argument), and you must specify the parameter name at the beginning of the second argument when calling the method. In Swift3.0, either the function or the method must specify the parameter name starting from the first argument (you can certainly use "_" to explicitly indicate that the call is omitted).

// 从第一个参数就必须指定参数名,除非使用"_"明确指出省略参数func sum(num1:Int,num2:Int)->Int{ return num1 + num2}sum(num1: 1, num2: 2) // old: sum(1,2)或者sum(1, num2: 2)
    • Cancel Var parameter
//func increase(var a:Int){//    a += 1//}// 上面的代码会报错,可改写成func increase(a:Int){ var a = a a += 1}
    • InOut parameter modification before type
//func increase(inout a:Int) {//    a += 1//}// 上面的代码会报错,可改为func increase( a:inout Int) { a += 1}
Method return value

The return value of the method in Swift 3.0 must be received or the warning will be reported, but of course the main purpose is to avoid the developer forgetting to receive the return value, but in some cases it is not necessary to use the return value to ignore the return value using the "_" receive. Of course you can also add @discardableResult a declaration that tells the compiler that this method can not receive the return value.

structCaculator {FuncSum(A:int,b:int)int {return A + b} @discardableResult func func1  (a:int,b:int)->int {return A-B + Span class= "Hljs-number" >1}}let CA = caculator () Ca.sum (A: 1, B: 2) //this warns because the method has a return value but does not receive let _ = Ca.sum (A: 1, B: 2) //Use" _ "to receive useless return values CA.FUNC1 (a: 1, B: 2) //because Func1 added @discardableresult declaration, the   is not warned even if the return value is not received   
Optional type

Swift3.0 the optional type control is more rigorous, the implicit optional type and other types of operations are obtained after an optional type rather than an implicit optional type.

let a:Int! = 1let b = a + 1 // 此时强制解包,b是Int型let c = a // 注意此时c是Int? 在之前的Swift版本中c是Int!
Changes in Selector

Selector change in fact from 1.0 to 3.0 experienced a number of changes, from the earliest @Selector("method:") to the present #selector(method(param1:)) can be said to undergo several changes, fortunately it becomes more and more good, after all, string manipulation for grammar check is very helpless.

ClassMyClass {@objcfunc sum  (a:int,b:int), int {return A + b} Span class= "hljs-function" >func func1  () {let _ = #selector (sum (a:b:))}}< Span class= "hljs-comment" >//old:swift 2.2//class MyClass {// @objc func sum (a:int,b:int), Int {//return a + b//}////func func1 () {//Let _ = #selector (Sum (_ : b:)) //}//}        
Optional methods in the Protocol

Before Swift3.0, if you want to define an optional method in the protocol, you only need to add @objc to the protocol after the method uses the optional modifier, but Swift3.0 in addition to the Protocol requires @objc adornment, the optional method must also be decorated with @objc.

@objc protocol MyProtocol {    @objc optional func func1() //old: optional func func1() func func2()}
Cancel + + 、--operator
var d = 1d++ //报错,可以改写成 d += 1 或者 d = d + 1
Cancel C-style for loop
//for var i = 0 ;i < 10 ; i += 1 {//    debugPrint(i)//}// 上面的代码会报错,可改写成如下代码for i in 0 ..< 10 { debugPrint(i)}
SDK Class Library changes

We all know that Swift was born in the OBJECTIVE-C has developed quite mature situation, in order to ensure the smooth transition of OBJC developers to Swift, also because Swift is in the early stage, many class library and method naming are as far as possible and OBJC consistent, OBJC's shadow can be seen everywhere in developing iOS apps using Swift. But as a modern language Swift has made a change, and it shows that Swift will be completely free from OBJC's shadow in the future. This includes re-importing the foundation to eliminate type prefixes, method name deduplication, functions and methods to C-style, and so on.

Named
1. Remove the prefixLet URL1 =URL (String:"Www.cmjstudio.com")Let Isfileurl = Url1?. IsfileurlOld:url1.fileURL, now more focused on semanticsLet data1 =Data ()NSData2. Method names using verbs, other nouns, prepositions, etc. as parameters or removalvar array1 = [1,2,3]array1.append (contentsof: [4,5,6])//Old:array1.appendContentsOf ([4,5,6]) Array1.remove (at: 0) //old:array1.removeAtIndex (0)//3. Without ambiguity, try to eliminate duplicate let Color1 = uicolor.red () //Old:var Color1 = Uicolor.redcolor ()//4. Enumeration member first letter becomes lowercase let Label1 = UILabel () label1.textalignment =. Center //old:label1.textAlignment =. Center//5. The normal state of the button is removed let btn1 = UIButton () btn1.settitle ("Hello", for :  Uicontrolstate ()) //equivalent to normal state             
Go to C style

The introduction of many class libraries in the early stages of Swift's development still retains the OBJC style, but objc because of the root C language, many operations are not actually object and method operations but the function form of the C language. After the Swift3.0, this situation will change, and the global function will become some kind of method; some constant definitions will be represented by the members of an enumeration type.

Let Rect1 =CGRect (x:0, Y:0, Width:Max, Height:100)The following code will be an error, 3.0 completely abolish this class C styleLet Rect1 = CGRectMake (0, 0, 100, 100)IfLet Context1 =Uigraphicsgetcurrentcontext () {Cgcontext.fillpath (CONTEXT1)Old:cgcontextfillpath (context1!)}The change of GCDLet queue =Dispatchqueue (Label:"Myqueue") Queue.async { debugprint ("Hello world!")} //old://let queue = dispatch_queue_create ("Myqueue", nil)//dispatch_async (queue) {//DebugPrint (" Hello world! ") //} //The related constant definition is moved to the enumeration internal notificationcenter.defaultcenter (). Addobserver (self, selector: #selector ( Userdefaultchange ()), Name: userdefaults.didchangenotification, object: nil)//old: Nsnotificationcenter.defaultcenter (). Addobserver (Self, selector: #selector (Userdefaultchange ()), Name: Nsuserdefaultsdidchangenotification, Object:nil)           
Changes to the collection API
Let array1 = [1,2,3]Let next = Array1.index (after:0) //Old:let start = array1.startindex let next = Start.successor () let first= Array1.first {(element) Bool  in//Add New Method element > 1} letr = Range (0..<3) //old:let _ = Nsrange (loc ation:0, Length:3)///The following code must be executed in the controller to traverse the current view and its parent view for Subview in sequence (first: Self.view, Next : {$0?. Superview}) { debugprint (subview)}             
New floating-Point Protocol

Float, Double, and CGFloat use the new protocol, providing properties and methods that provide the IEEE-754 standard.

let a = 2 * Float.pi // old: let a = 2 * M_PIlet b = 2.0 * .pi // 注意前面是浮点型,后面可以省略Float

Of course there are some other infrequently used changes in Swift3.0, and if interested can access swift proposals

Migrating from Swift2.2 to Swift3.0

It can be seen that if you want to update to Swift3.0 existing projects need to make a lot of changes, after using the open source project Tageditor to test, a mere 10 classes of files have more than 100 errors, but in Xcode 8 has provided a very useful migration tool (Xcode:editor- Convert-to current Swift Syntax), after the migration tool was converted, only two errors were found to be manually corrected. When using this tool, you will see the following interface:

Swift 2.3? Yes, there's also a swift 2.3,apple in the middle of Swift2.2 and Swift 3.0 explaining what Swift 2.3 is, in fact, Swift 2.2 + New SDKs. This is because Xcode 8 is currently a beta version, and apps developed with Swift 3.0 are not yet submitted to the app Store, so using the new SDK development on Swift 2.2 is still necessary.

Summarize

Every change in swift, which is incompatible with the previous version and even the previous version, makes every swift upgrade a bit more masochistic, but in fact it is a major step forward for Swift. There was a rumor that Swift3.0 's grammar and API would be stable and up-to-the-top, but soon the news was dashed, and the WWDC officially confirmed that the hope was likely to reach 4.0. But imagine: is Apple really a good thing about the development of the fixed-line API for Swift in a short period of time? After all, the addition of new features, better grammar optimization to make swift better! In general, if your app is going to be upgraded to Swift3.0, you might want to make varying degrees of change, but it's just that the syntax and SDK changes don't consume too much work, not to mention that Apple provides a migration tool.

iOS Development Series--swift 3.0

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.