Swift 2.0 in the end, where is "new"?

Source: Internet
Author: User



"Editor's note" June 2015, the annual Apple WWDC Conference as scheduled, at the conference, Apple released the Swift 2.0, introduced a lot of new features, to help developers to build applications faster and more easily. The author of this article is Maxime Defauw, the Maxime of this article gives you a brief introduction to the notable new features of Swift 2.0. This article is compiled and collated by OneAPM engineers.



A year ago, Apple launched a new programming language--swift for IOS and OS x. When I heard it released, like millions of IOS developers, the author's inner excitement. As the propaganda says, Swift has grown into one of the most popular programming languages as a fast and secure programming language. A year later, Apple did not live up to expectations and launched Swift 2.0 at the WWDC meeting in 2015. The author had the pleasure of going to the scene, so here is a brief introduction to the new features of Swift 2.0.



"This year, we will be using Swift 2.0 to ride the waves. We believe Swift is about to become the largest programming language and the most indispensable application and system programming language for the next 20 years. Anyone can use swift"anywhere, says Craig Federighi, vice president of software engineering at Apple.






At the WWDC conference, Apple measured the popularity of new features in decibels. The two biggest applause in the meeting was that Apple announced that Xcode 7 supported the UI test and the other was Swift's open source. If you miss WWDC's keynote speech, or your recent life under pressure, then check again, you're not mistaken: Swift is really open source. It's a big thing! In the second half of the year, Apple will also publicly release the source code for Swift under the OSI Standard license, including compilers and standard libraries. Apple will also open the source code port for Linux, and developers will be able to promote language development and write Swift programs on Linux. As a result, Apple is encouraging developers to push the development of Swift further.



With this exciting news release, Swift 2.0 covers more new features such as error handling for upgrades, protocol extensions, and usability checks. Let's take a look at these new features.


Error handling


The program always goes wrong. When there is a problem with the function, if you can find out what went wrong, you can understand why the exception occurred. The Swift 1.0 version lacks an effective error handling mechanism. In Swift 2.0, developers can use the Try/throw/catch keyword to create exception handling patterns.



Suppose you are joining a car engine model. The engine may cause failure for some reason:


    • no oil;
    • Oil spills;
    • Low power.


In Swift, errors can be considered as type values that conform to the ErrorType protocol. In this case, you can create an enumeration model that conforms to ErrorType to represent the error scenario:


 
 
enum CarEngineErrors: ErrorType {
    case NoFuel
    case OilLeak
    case LowBattery
}


Construct a function that throws an exception, using the throws keyword in the declaration, as shown in the following example:


funccheckEnginethrows{}


The function throws an error, you can use the throw declaration. The following example code demonstrates a simple check of engine errors:


 
 
let fuelReserve = 20.0
let oilOk = true
let batteryReserve = 0.0

func checkEngine() throws {
    guard fuelReserve > 0.0 else {
        throw CarEngineErrors.NoFuel
    }

    guard oilOk else {
        throw CarEngineErrors.OilLeak
    }

    guard batteryReserve > 0.0 else {
        throw CarEngineErrors.LowBattery
    }
}


The Guard keyword is the first reference to the Swift 2.0 for enhanced control flow. When a guard statement is executed, the conditional statement is first checked. If the condition is false, the else part is executed. In the above code, if no conditions are met, the function throws an exception.



In order to invoke the throw function, the Try keyword needs to be placed before the function call.


 
func startEngine() {
    try checkEngine()
}


If you write the above code in Playgrounds, an error has occurred before handling the exception. The error handling mechanism in Swift requires the use of Do-catch statements to fetch exceptions and handle them appropriately.



The following function specifies the response after catching an exception:


func startEngine() {
    do {
        try checkEngine()
        print("Engine started", appendNewline: true)
    } catch CarEngineErrors.NoFuel {
        print("No Fuel!")
    } catch CarEngineErrors.OilLeak {
        print("Oil Leak!")
    } catch CarEngineErrors.LowBattery {
        print("Low Battery!")
    } catch {
        // Default
        print("Unknown reason!")
    }
}


Each catch clause matches a specific error and specifies the response mechanism for the related error. In the above example, the Batteryreserve variable is set to 0, in which case the call to StartEngine () will be thrown. Lowbattery exception.



If the Batteryreserve reset to 1.0, so that there is no exception to throw, window printing "engine started" prompt information.



Similar to the switch statement, the error handling mechanism of Swift 2 is complete and you need to consider all possible error conditions. So we need to include a catch clause that does not specify a type.



If you need to know more about Swift's error handling mechanism, we recommend that you refer to Apple documentation.


println () function absent


When the author wrote this introduction, he noticed the absence of the println () function. In Swift 2.0, we can print to the Output window with just the print () function. Apple merged the println () and print () functions. If you want to output interlaced, you can set the Appendnewline parameter to True. As shown in the following code:


print("Engine started"true)
Protocol Extensions


In the older version of Swift, you can use extensions to add new functionality to an existing class, struct, or enumeration. Swift 2.0 allows developers to extend the application to the protocol type. As the protocol expands, you can add functions or properties to all classes by adding a specific protocol, and also facilitate extending the functionality of the Protocol.



Create a new protocol and name it Awesome, as shown in the following example. The protocol can be implemented by any type that can return a percentage of the awesomeness exponent of a particular object.


protocol Awesome {
    func awesomenessPercentage() -> Float
}


Now declare two classes that comply with the new agreement. Each class implements the specified method of the Awesome protocol:


 
class Dog: Awesome {
    var age: Int!
    func awesomenessPercentage() -> Float {
        return 0.85
    }
}

class Cat: Awesome {
    var age: Int!
    func awesomenessPercentage() -> Float {
        return 0.45
    }
}

let dog = Dog()
dog.awesomenessPercentage()

let cat = Cat()
cat.awesomenessPercentage()


Initialize the class in Playground and call the Awesomenesspercentage () method, and you will see the following output:






If you want to add a Awesomenessindex property to extend the Awesom protocol, you can use the results of the Awesomenesspercentage method to calculate the awesomeness value. The code is as follows:


extension Awesome {
    var awesomenessIndex: Int {
        get {
            return Int(awesomenessPercentage() * 100)
        }
    }
}


Create an extension in the protocol, and all classes that follow the Awesome protocol can access the Awesomenessindex property.






It's really cool, isn't it?


Usability Checks


Developers know that building apps needs to struggle with different versions of IOS at all times. You always want to use the latest version of the API, but sometimes running on an older version of IOS is prone to errors, which can lead to bugs. Prior to Swift 2.0, there was no standard way to perform usability checks. For example: The Nsurlqueryitem class is available on iOS 8, and if used in previous versions of iOS, it can be an error, or even cause the app to crash. To avoid this error, you can perform an availability check in the following code:


 
if NSClassFromString("NSURLQueryItem") != nil {
    // iOS 8 or up
} else{
    // Earlier iOS versions
}


This is a way to check if a class exists. Starting with Swift 2, the availability check for APIs under different versions is supported. You can simply define an availability condition so that the corresponding code block can only be executed under a specific IOS version, for example:


 
if #available(iOS 8, *) {
    // iOS 8 or up
    let queryItem = NSURLQueryItem()

} else {
    // Earlier iOS versions

}
Do-while Change to Repeat-while


The classic Do-while cycle is now renamed Repeat-while, please refer to the following example:


 
var i = 0
repeat {
    i++
    print(i)
} while i < 10
Summarize


I hope you enjoy this introduction to Swift 2.0. There are a lot of things that are not covered, such as annotations in Markdown format. For more details, refer to this WWDC video. Here, many companies are still using OBJECTIVE-C as the main programming language for building IOS apps, and most likely you are. But the authors remain convinced that Swift's prospects for development are broader. In fact, all the major conferences in WWDC in 2015 are using swift, and if you haven't learned swift yet, it's time to take action!



You can download the Playground file for this article here. Make sure that you run the code with Xcode 7, which is the only version of Xcode that supports Swift 2.0. Xcode 7 is still in the beta phase. You can download it from the Apple official website.



Original address: What's New in Swift 2.0:a Brief Introduction



OneAPM is the emerging leader in the field of application performance management. Mobile Insight helps monitor the performance of mobile applications by measuring the actual user experience and detecting the occurrence of each crash. To read more technical articles, please visit the OneAPM official blog.



Swift 2.0 in the end, where is "new"?


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.