Swift 3.0, a lot of noise, but what really is?



    In early May, on the Internet, the language developers announced that they were starting preparations for the release of the 3.0 version of the language. Development 3.0 is in the master branch, according to releases, you can understand that on May 3rd there was a release of Swift 2.2.1. Then, changes to the 3rd version of the language began to be poured there. On May 9, the first developer release from the same wizard appeared, which can be rolled over to the latest xcode through the installer from swift.org/download/#snapshots , which is enabled through Preferences -> Components -> Toolchains.

    Some general information about the upcoming release


    Around the first dev release of Swift 3.0, the developers said that, unfortunately, they did not have time to implement ABI compatibility in the 3.0 version. Let's figure out what this all means, for the first time I myself saw these three letters together.

    ABI is an application binary interface, roughly speaking it is the compatibility of binaries of different versions among themselves, we can give an analogy with the usual API compatibility when API 1.0 is compatible with 2.0, but changes made in 3.0 will already be incompatible with the first version, so when using the API 3.0 you will need to edit the code (in the case of ABI, do not edit the code, but rebuild the binary).

    In fact, as it turned out to be a discovery for me, Swift has never had an ABI compatibil. This suggests that the lib built on Swift 2.0 will no longer be resolved with the 2.2 version of the language. Colleagues from stable languages:



    This is how it turns out and we live. But sweaters and sivivers in this regard were lucky, because the Dependence managers (cocoapods, carthage) always pull up the project sources, not the binaries, so there are no problems with ABI compatibility as such. But, apparently, it’s worthwhile to refrain from writing proprietary libs on the sfivt and put them in public in the form of binaries. Yes, they promise to add ABI only to Swift 4.0.

    Let's look at the changes in the API




    Even the didFinishLaunching method is highlighted by warning, since his signature has changed, now he has become

    /// swift 3
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]? = [:]) -> Bool {}
    /// swift 2
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {}
    

    Warnings should be easily fixed for migration to Swift 3.0 in Xcode in the future.

    Let's look at the changes in the standard Swift library and in Foundation


    ErrorType changed to ErrorProtocol

    /// swift 3
    enum MyError: ErrorProtocol {
        case Success
        case Fail(ErrorProtocol)
    }
    /// swift 2
    enum MyError: ErrorType {
        case Success
        case Fail(ErrorType)
    }
    


    Changes for Array

    /// swift 3
    sort() // сортирует сам себя
    sorted() // сортирует и возвращает новый отсортированный массив не изменяя порядок в старом
    /// swift 2
    sortInPlace() // сортирует сам себя
    sort() // сортирует и возвращает новый отсортированный массив не изменяя порядок в старом
    


    that is, the sort method became mutable, removed sortInPlace and added sorted .

    /// swift 3
    reversed()
    append(contentsOf: [T])
    insert(T, at: Int)
    joined(separator: String)
    /// swift 2
    reverse()
    appendContentsOf([T])
    insert(T, atIndex: Int)
    joinWithSeparator(String)
    

    Also removed many designers and renamed other methods.

    Changes for String

    /// swift 3
    "3.0".components(separatedBy: ".")
    "3.0".substring(to: 1)
    "3.0".substring(from: 1)
    "".data(using: NSUTF8StringEncoding)
    "2.0".replacingOccurrences(of: "2", with: "3")
    "".uppercased()
    "".lowercased()
    "3.0".contains(".")
    "3.".appending("0")
    ("dir1" as NSString).appendingPathComponent("dir2")
    " 3.0 ".trimmingCharacters(in: .whitespaces())
    "".write(toFile: "/..", atomically: true, encoding: NSUTF8StringEncoding)
    /// swift 2
    "3.0".componentsSeparatedByString(".")
    "3.0".substringToIndex(1)
    "3.0".substringFromIndex(1)
    "3.0".dataUsingEncoding(NSUTF8StringEncoding)
    "2.0".stringByReplacingOccurrencesOfString("2", withString: "3")
    "".uppercaseString
    "".lowercaseString
    "3.0".containsString(".")
    "3.0".appendContentsOf(".release")
    ("dir1" as NSString).stringByAppendingPathComponent("dir2")
    "3.0".stringByTrimmingCharactersInSet(.whitespaceCharacterSet())
    "3.0".writeToFile("/..", atomically: true, encoding: NSUTF8StringEncoding)
    


    Cases for enum are now in the lover case

    /// swift 3
    UIInterfaceOrientation.portrait
    Optional.some("")
    Optional.none
    /// swift 2
    UIInterfaceOrientation.Portrait
    Optional.Some("")
    Optional.None
    


    Changes in UIKit


    /// swift 3
    let vc = UIViewController()
    vc.present(some, animated: true, completion: nil)
    vc.dismiss(animated: true, completion: nil)
    vc.prepare(for: segue sender: button)
    UIColor.white()
    UIColor.blue()
    let path = UIBezierPath()
    path.move(to: CGPoint(x: 0, y: 0))
    path.addLine(to: CGPoint(x: 100, y: 100))
    // добавился знак _ в начале первого параметра + сократили имя аргумента функции, из-за чего будут варниги в проекте
    func tableView(_ tableView: UITableView, numberOfSections section: Int) -> Int { return 0 }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: NSIndexPath) -> UITableViewCell { return UITableViewCell() }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: NSIndexPath) { }
    /// swift 2
    let vc = UIViewController()
    vc.presentViewController(some, animated: true, completion: nil)
    vc.dismissViewControllerAnimated(true, completion: nil)
    vc.prepareForSegue(segue, sender: button)
    UIColor.whiteColor()
    UIColor.blueColor()
    let path = UIBezierPath()
    path.moveToPoint(CGPoint(x: 0, y: 0))
    path.addLineToPoint(CGPoint(x: 100, y: 100))
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return UITableViewCell() }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { }
    


    More changes


    /// swift 3
    NSData(contentsOf: "")
    UIApplication.shared()
    NSUserDefaults.standard().set("value", forKey: "key")
    NSFileManager.default().fileExists(atPath: "/...")
    NSBundle.main()
    /// swift 2
    NSData(contentsOfURL: "/")
    UIApplication.sharedApplication()
    NSUserDefaults.standardUserDefaults().setObject("value", forKey: "key")
    NSFileManager.defaultManager().fileExistsAtPath("/")
    NSBundle.mainBundle()
    


    This is how swiftification was performed, in general, the whole api was damaged, and not just the standard library. But I must admit, readability really got better. Release Swift 3.0 is scheduled for fall. ABI compatibility is scheduled for 4.0. Something new in Swift should not be expected at WWDC 2016. The

    question is, so what is all the same to choose for a new project? I vote for Swift, with it development is much faster and safer due to the very strict typing and loops in the form of Optional and the syntax of closures / lambdas. In general:



    Useful links:

    https://swift.org/blog/
    https://www.hackingwithswift.com/swift3
    https://github.com/apple/swift-evolution
    http://www.bensnider.com/ abi-compatibility-whoopdty-do-what-does-it-all-mean.html

    update

    It is worth adding that Swift developers shoveled the entire API to make it as it was intended from the first days of the language, just support for compatibility with Objective-C did its job and broke the original API design. It is planned that Swift will work on many platforms, including FreeBSD, Raspberry Pi, Android, Windows. Apparently, it was in version 3.0 that they decided to make a complete redesign of the API, to give it a more swift style.

    Only registered users can participate in the survey. Please come in.

    try?

    • 43% for hipsters, I'll wait for stable version 268
    • 14.7% fix for incompatibility and I will continue to transfer old objc projects to it and write new ones 92
    • 26.3% fix for incompatibility, but I will use it only in new projects, objc will leave it as it is 164
    • 10.1% would like, but the business does not give :( 63
    • 5.6% other, I will write in kamenty 35

    Also popular now: