Swift 3 Migration Summary

Source: Internet
Author: User





Source: Damonwong (@ Wang Yi-jian)

Links: http://www.jianshu.com/p/f4761952b8c2





Write in front





    • The SWIFT 3.0 release has been released for almost one months, with intermittent handles and swift-related migrations to Swift 3.0. So write a little summary.





Background






Code amount (40,000 lines)





    • First of all, I began to start Swift at the beginning of this year. Coupled with Swift's ABI and API has been unstable, so there is no large-scale use of the project, so this migration of code is not much, about 40,000 lines.





Migration time (around one day)





    • It took about 1 days to move in time. Two mixed projects, a Swift-based project. Interim Swift-based projects took about half a day, two mixed code, but a small half a day, and a little more than half an hour (reason to leave a suspense ~).





Get ready





Many of the decisions that were made during the initial development of the choice of Swift also left me with a lot less work this time.





Interface with xib instead of pure code





    • Quirks, most of the interfaces associated with Swift are painted with xib. And this xib has a great advantage in this migration, Xib and SB's code does not fit with Swift 3. If you want to use the code to write the UI, the migration changes are estimated to be much more.





About the selection of third-party libraries:





    • For a project, the three-way library seems to be a must-choose dish, but how to choose this dish?

    • For the three-party library, the original choice is that you can use OC to try to use OC. After all, OC can seamlessly connect to Swift, and it is relatively stable.

    • When choosing a three-way Swift-related library, I try to value more libraries, such as Alamofire, Snap, Kingfisher, Fabric, etc., because users are more likely to be more willing to maintain, rather than skip tickets. So there is no problem for many small partners now, want to migrate, but some libraries are not updated. At least for me, when I want to migrate, all the three-party libraries associated with Swift have migrated to 3.0.




Thanks to the above two points, there is a lot less work during the migration process.





Knowledge Reserve Upgrade





    • Let's look at the changes in Swift 2 to Swift 3 and the reasons for the change. (10,000 grass mud horse flies through the heart, but in fact it is getting better)

      • Swift Gumbo: https://swift.org/

      • Swift-evolution:https://github.com/apple/swift-evolution/blob/master/releases/swift-3_0.md

      • Swift 3 new features at a glance: https://realm.io/cn/news/appbuilders-daniel-steinberg-whats-new-swift-3/

    • Then the grammar document was quickly revisited.

      • Swift Programming language:https://developer.apple.com/swift/

      • Chinese version: http://wiki.jikexueyuan.com/project/swift/


Issues in the migration






Any && Anyobject





  • I want to do the migration and the migration of the students to change the most one is as anyobjct? , huh?
  • At least for me, yes.
  • And this related basic is the collection type. In Swift 2 we used [Anyobject] to store any variables, even strings of struct types, arrays, and so on. However, the anyobject of Swift refers to a class, and any is a struct, class, Func, and so on. But why would a Struct fit into [Anyobject]? In Swift 2, a implicit bridging Conversions is performed for structs such as String, Int, and so on. In the case of Swift 3, a **fully eliminate implicit bridging conversions from swift** was made.

  • Of course in my project [Anyobject] is actually small, the most troublesome is [string:anyobject]. Because when writing the project, or in the OC to Swift stage so for Dictionary, the basic use of [string:anyobject], so in the revision, in many places for this change.

      • At first, I followed Xcode's hint and added an as anyobjct behind the value of Dictionary.

      • Then gradually found that I did a very silly thing, in fact, I just put [string:anyobject] to [String:any] on it.

  • That's why I spent so much time modifying the code in the first mixed project! The second project, which benefited from a mixed study, Yep the idea of naming [String:anyobject] as a type called jsondictionary. So in any && anyobect this thing, it took a little time.


Swift 2



var json = [<span class="Hljs-link_label">String: Anyobect </span>] ()



JSON["Key1"] = 1



JSON["Key2"] = "2"






To Swift 3 Step 1



var json = [<span class="Hljs-link_label">String: Anyobect </span>] ()



JSON["Key1"] = 1 as anyobject?



JSON["Key2"] = "2" as anyobject?






To Swift 3 Step 2



var json = [<span class="Hljs-link_label">String: any </span>] ()



JSON["Key1"] = 1



JSON["Key2"] = "2"






Swift 2



Public Typealias Jsondictionary = [String: Anyobject]



To Swift 3 Step 2



Public Typealias Jsondictionary = [String: Any]






Alamofire and other three-party library support IOS8





    • Although I used the three-way library to upgrade the library to Swift 3 the first time, but the mid-alamofire and Snap Two libraries are only supported to IOS 9, in order to avoid and product tearing, have to find a way to solve this adaptation problem. Let's take alamofire as an example

    • In fact, the three-party library, not necessarily only with Cocoapods. So plan to download the code and then direct the source.

    • First Alamofire Xcode is modified to a minimum of 8.0, and then compiles a function that does not pass, and deletes. (In fact, these functions are all new IOS 9 functions, so the deletion does not affect anything.) )

    • It takes about half an hour or so to be erased and then dragged directly to the project.

    • Snap is just a matter of dragging it in, so there's no need to change anything at the moment.





In fact, all!os (WatchOS) under this macro



#if!os (WatchOS)






@Discardableresult



public func stream(withhostname hostName: String, port: Int) Streamrequest {



return sessionmanager. Default. Stream(withhostname: HostName, port: Port)



}






@Discardableresult



public func stream(with netservice: Netservice) , streamrequest {



return sessionmanager. Default. Stream(with:netservice)



}






#endif






@escaping





    • This is the most painful pit I've had in my fitness match.

    • First look at Swift-evolution just understand that @escaping must show the declaration. But do not know @escaping's closure, in the function body can not be modified.





let pedonmeter: Cmpedometer = cmpedometer()






func getpedometerdatafromdate(_ datet:D ate?, withhandler handler: @escaping (cmpedometerdata?, Error?) ()) {









//Compilation error



pedonmeter. Querypedometerdatafromdate(startTime, toDate: EndTime, withhandler: { ( pedometerdata: Cmpedometerdata?, error: Nserror?) - Void in






guard Let pedometerdata = pedometerdata else { return }



handler(pedometerdata, error)






//Do some things






})



//finally forced to change only, the function outside to do something



pedonmeter. Querypedometerdata(from:starttime, to:endtime, withhandler:handler as ! cmpedometerhandler)






}






Result of call to ' funtion ' is unused





    • This is not actually a compilation error, but the warning was a bit confusing at first. Return value don't you want me to change it?

    • In the beginning, I was so modified let _ = Funtion (), but later in the look at SE-0047 found @discardableresult can also achieve this effect.





Date && NSDate





    • Because there is a project that uses the Datetools tool. It has a classification of NSDate + Tools.

    • But in the process of writing Swift 3, I discovered that if a variable is of type date, you cannot use NSDate + Tools, you must display some methods that declare date as NSDate so that you can call the classification.

    • This allows the use of OC library when it feels very uncomfortable, after all, a lot of NS prefix removed. All the statements are too unfriendly to show.





Caanimationdelegate





    • This actually seems to be a modification of Xcode 8. Because before Caanimationdelegate is a classification. The following is probably stated:




@interface nsobject (caanimationdelegate)


- (void)animationdidstart:(caanimation *)anim;

-

- (void)animationdidstop:(caanimation *)Anim finished :(BOOL)flag;


@end




    • Before is in the VC, just rewrite the Animationdidstart function can be. But the new is not, initially thought to be Swift 3 change, but in fact is the modification in Xcode 8. Turning caanimationdelegate into a protocol. I feel that this modification is for the purpose of matching Swift 3? The changes are as follows:




@protocol caanimationdelegate <NSObject>

@Optional


- (void)animationdidstart:(caanimation *)anim;

-

- (void)animationdidstop:(caanimation *)Anim finished :(BOOL)flag;


@end




Because the width of the time is longer, the other temporarily can't think of. It's not too soon to be continued ...





Other





    • There are many subtle changes that make it seem like you don't understand the language, so it's recommended to take a look at the following article before adapting.

      • Swift 3 new features at a glance: https://realm.io/cn/news/appbuilders-daniel-steinberg-whats-new-swift-3/

      • [Swift 3.0–released on September, 2016]HTTPS://GITHUB.COM/APPLE/SWIFT-EVOLUTION/BLOB/MASTER/RELEASES/SWIFT-3_0.MD

      • And the Swift 3 must-see series of Students @ Zhuo: http://www.jianshu.com/notebooks/6709594/latest

    • And a couple of good summaries.

      • Swift 3 by Gupeng: http://tech.glowing.com/cn/swift3/

      • A little bit of experience with the Swift 3 and pit by Tula Tripod: https://zhuanlan.zhihu.com/p/22584349


Summarize





    • Overall this migration is not as painful as it might seem, although the proposal has changed a lot, but thanks to the Xcode 8 migration Tool, this migration takes a little time, and of course it may be related to my Code size ~

    • After the migration, look at the code, you will find that Swift more elegant, at least compared to the second agreed a lot, as good as where? You'll know if you write it yourself.

    • Finally, can finally put the XOCDE 7 uninstall, no longer worry about two open no brain flash back!!!

    • Finally for next year's Swift 4 just want to say come on ~ ~ Minute to solve you!

    • In fact, the path of adaptation is just beginning, because the Xcode 8 auto-transcoding code does not have a very good Swift 3. At the moment it's just that the Swift 3 can be compiled and passed.





More






After work, write a few notes, if necessary can be seen on my GitHub.



Https://github.com/Damonvvong/iOSDevNotes



Swift 3 Migration Summary


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.