Brief Introduction to Swift 2.0

Source: Internet
Author: User

Brief Introduction to Swift 2.0

I have read many articles about Swift 2.0, and I feel that Appcoda is quite clear in this article. I learned and translated it by hand. For the original English text, I will read it here.

What's New in Swift 2.0: A Brief Introduction

A year ago, Apple brought a brand new programming language Swift to iOS and OSX developers. When Apple's Vice President announced it at WWDC, I was just as excited as many developers. Swift has grown into the most popular language for faster and safer publicity. Apple launched Swift 2 at WWDC this year. I am lucky to attend this WWDC conference. I will share some updates to the new version of Swift.

We’re stepping on the gas this year with Swift 2. We think Swift is the next big programming language, the one we will all do application and systems programming on for 20 years to come. We think it should be everywhere and used by everyone.

Craig Federighi, Apple’s senior vice president of Software Engineering

I noticed two major applause at the WWDC venue. One was Apple announcing that Xcode 7 supports UI testing, and the other was that Swift would open source code, which would be a big event, later this year, Apple will develop the Swift source code to the public, including the compiler and some basic libraries, all under the OSI-compliant license. Apple will also allow Swift to support Linux. developers can use Swift to write system applications. This shows that Apple has finally begun to work hard to promote the development of this new language.

Aside from these exciting news, Swift 2 introduced some new features, such as error handling, protocol extensions, and availability check ), next we will introduce it in detail.

Error Handling

There will always be errors in the program. When a function fails, if you can find out what went wrong, it helps to understand why it failed. Swift version 1 lacks an appropriate error handling mode. In Swift 2, the exception handling mode is added and the try/throw/catch keyword is used.

Imagine a car engine that fails to start due to the following reasons:

  • No fuel)
  • Oil leakage)
  • Low battery)

In Swift, errors can be viewed as observedErrorTypeProtocol type. Accordingly, you can create a complianceErrorTypeTo indicate the preceding error conditions:

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

To create a function that can throw an exception, you can use the throws Keyword:

func checkEngine() throws {}

To throw an error in a function, you can use the throw statement. The following example shows how to check the engine:

let fuelReserve = 20.0let oilOk = truelet batteryReserve = 0.0func 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 Swift 2 to enhance the control flow (Control flow. When the guard statement of the Control Branch is executed, the condition statement followed by the guard statement is checked first. If the condition is false, the else part will be executed, in the preceding example, if the condition is false, an exception is thrown when the throw statement is executed.

To call the throwing function, you need to put the try keyword before the function name:

func startEngine() {    try checkEngine()}

If you write the above Code in Playgrounds, you will get an error. Swift's error handling mechanism requires you to use the do-catch statement to capture all the errors and process them.

The following function specifies to print the relevant error information after capturing the relevant error:

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 what should be done after an error is captured. In the preceding example,BatteryReserveThe variable is set to 0. In this case, runstartEngine(),.LowBatteryAn error will be thrown.

SetBatteryReserveChange to 1.0, so that there will be no errors when the car starts.

Similar to the switch statement, the error handling model of Swift 2 is also required to be complete, meaning that you must handle all possible errors. This is why we need to include the last one without any matching pattern.catch

If you want to learn more about Swift error handling, I recommend that you read the official Apple documentation.

No More println ()

You may have noticed this.println()The function is missing. In Swift 2, we can only useprint()To print the output. Appleprintln()Andprint()Merge into one. If you want to print a new row, you can setappendNewlineThe parameter istrue

print("Engine started", appendNewline: true)
Protocol Extensions

In the first version of Swift, you can use extensions to add new functions for existing classes, struct, and enumeration types. Swift 2 allows developers to bring extensions to the protocol type. With Protocol Extensions, you can add properties or functions for classes that comply with a certain Protocol. It will become very useful when you want to extend the capabilities of protocol.

Let's use an example to illustrate how to create an Awesome protocol that provides an exaggerated percentage of awesomeness returned. Any object that implements this method can be considered to follow this Protocol:

protocol Awesome {    func awesomenessPercentage() -> Float}

Now we declare that two classes comply with thisAwesomeProtocol, each class implements the Protocol method:

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()

If you are demonstrating in Playground, you will get the following output:

If you wantAwesomeAdd an awesomenessIndex attribute for the protocol. We will use the awesomenessPercentage () method to calculate the awesomeness index:

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

By creating extension on the protocol, all classes that follow the protocol can immediately access the awesomenessIndex index.

Isn't it a wonderful O (∩ _ ∩) O ~~

Availability Checking

Every developer must fight against different iOS versions when building an App. You always want to use the latest API, but some errors may occur when the APP runs on iOS. Before Swift 2, there was no way to stick to the iOS version. For example, the NSURLQueryItem class can only be used on iOS 8. If you use it in the previous iOS version, an error is immediately returned and crash is dropped. To prevent this event, you can perform the following check:

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

This is a way to check whether a class exists. Starting from Swift 2, you can check the availability of the API in a specific version. You can easily define a availability condition, then, execute the specific Code related to the iOS version under the corresponding code block:

if #available(iOS 8, *) {    // iOS 8 or up    let queryItem = NSURLQueryItem()} else {    // Earlier iOS versions}
Do-while is now repeat-while

The classic do-while loop is now renamed as repeat-while, And the semantics is clearer:

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

I hope you will be happy to read the official introduction to Swift 2. There are many content that I did not mention in this article, such as the Markdown format annotations, you can also watch the WWDC video to learn more about Swift 2. At this moment, many companies still use Objective-C as the main language for iOS development. Maybe you are using OC. But I strongly believe that Swift is the path to the future. In fact, all sessions of WWDC 2015 are using Swift, So if you haven't learned Swift, start now.

You can download the Playground file code of this Article. Make sure to run it in Xcode 7, because this is the only Xcode version that supports Swift 2.0.

Apple Swift tutorial

Use Swift to build an iOS email application

Swift 2.0 open-source

Swift details: click here

This article permanently updates the link address:

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.